404b53bd571f7a094995b194686488dfb1fc7529
[apps/web/sample/ContactsExchanger.git] / project / js / app.js
1 /*
2  *      Copyright 2013  Samsung Electronics Co., Ltd
3  *
4  *      Licensed under the Flora License, Version 1.1 (the "License");
5  *      you may not use this file except in compliance with the License.
6  *      You may obtain a copy of the License at
7  *
8  *              http://floralicense.org/license/
9  *
10  *      Unless required by applicable law or agreed to in writing, software
11  *      distributed under the License is distributed on an "AS IS" BASIS,
12  *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *      See the License for the specific language governing permissions and
14  *      limitations under the License.
15  */
16
17 /*jslint devel: true*/
18 /*global $, tizen, Config, localStorage */
19
20 var App = null;
21
22 // App instance
23 var app = null;
24
25 (function () { // strict mode wrapper
26     'use strict';
27
28     /**
29      * Creates a new application object
30      *
31      * @class Application
32      */
33     App = function App() {};
34
35     App.prototype = {
36         nfcAdapter: null,
37         addressBook: null,
38         started: false,
39         timeOutHandler: null,
40         counterState: true,
41         nfc: null,
42
43         init: function appInit() {
44             this.config = new Config();
45             this.ui = new App.Ui(this);
46             this.nfc = new App.NFCControl(this);
47             this.ui.defineEvents();
48             this.initAddressBook(this.nfc.startNFC.bind(this.nfc));
49         },
50
51         saveDefaultCard: function saveDefaultCard() {
52             var elementSelected = $('#list-choose li.selected');
53             localStorage.started = true;
54             localStorage.id = elementSelected.data('id');
55             localStorage.caller = elementSelected.data('caller');
56             localStorage.firstName = elementSelected.data('firstName');
57             localStorage.middleName = elementSelected.data('middleName');
58             localStorage.lastName = elementSelected.data('lastName');
59             localStorage.phoneNumber = elementSelected.data('phoneNumber');
60             localStorage.vCard = elementSelected.data('vCard');
61             this.started = true;
62
63             $.mobile.changePage('#start');
64         },
65
66         updateDefaultCard: function updateDefaultCard(contact) {
67             localStorage.caller = this.ui.prepareCallerName(contact);
68             localStorage.firstName = contact.name.firstName || '';
69             localStorage.middleName = contact.name.middleName || '';
70             localStorage.lastName = contact.name.lastName || '';
71             localStorage.phoneNumber = contact.phoneNumbers[0].number;
72             localStorage.id = contact.id;
73             localStorage.vCard = contact.convertToString('VCARD_30');
74         },
75
76         /**
77          * @param {Array} addressbooks
78          */
79         getAddressBooksSuccess: function getAddressBooksSuccess(addressbooks) {
80             if (addressbooks.length > 0) {
81                 var self = this,
82                     resetLocalSorage = function () {
83                         // Reset localStorage
84                         localStorage.clear();
85                         self.started = false;
86
87                         // Load start page with temporary content
88                         self.ui.moveToStartPage();
89                         self.ui.loadTemporaryContent();
90                     };
91                 this.addressBook = addressbooks[0];
92
93                 if (localStorage.id) {
94                     try {
95                         this.updateDefaultCard(
96                             this.addressBook.get(localStorage.id)
97                         );
98                     } catch (err) {
99                         if (err.name === 'NotFoundError') {
100                             resetLocalSorage();
101                         }
102                     }
103                 }
104
105                 // Registers to be notified when the address book changes
106                 this.addressBook.addChangeListener({
107                     oncontactsadded: function (contacts) {
108                         // Refresh if choose page active
109                         self.ui.refreshIfActivePage('choose');
110                     },
111                     oncontactsremoved: function (ids) {
112                         // Refresh localStorage if default contact was deleted
113                         if (ids.indexOf(localStorage.id) >= 0) {
114                             resetLocalSorage();
115                             alert('Your default contact has been removed. ' +
116                                 'Please choose another one.');
117                         } else {
118                             // Refresh if choose page active
119                             self.ui.refreshIfActivePage('choose');
120                         }
121                     },
122                     oncontactsupdated: function (contacts) {
123                         var index = contacts.length;
124
125                         // check if default contact was updated
126                         while (index - 1) {
127                             if (contacts[index].id === localStorage.id) {
128                                 try {
129                                     self.updateDefaultCard(contacts[index]);
130                                 } catch (e) {
131                                     resetLocalSorage();
132                                     alert('That contact is no longer valid. ' +
133                                         'Choose another one.');
134                                 } finally {
135                                     break;
136                                 }
137                             }
138                             index -= 1;
139                         }
140
141                         self.ui.refreshIfActivePage('start');
142                     }
143                 });
144             } else {
145                 console.error('initAddressBook failed');
146             }
147         },
148
149         /**
150          *
151          * @param {Error} e
152          */
153         getAddressBooksError: function getAddressBooksError(e) {
154             console.error('getAddressBooks() error: ' + e.message);
155         },
156
157         initAddressBook: function initAddressBook(callback) {
158             try {
159                 tizen.contact.getAddressBooks(function (addressbook) {
160                     this.getAddressBooksSuccess(addressbook);
161                     callback();
162                 }.bind(this),
163                     this.getAddressBooksError.bind(this));
164             } catch (e) {
165                 if (e.name === 'SecurityError') {
166                     this.ui.showPopupWarning();
167                 }
168                 console.error('getAddressBooks() error: ' + e.message);
169             }
170         },
171
172         countDown: function countDown(time, obj) {
173             if (!this.counterState) {
174                 setTimeout(function () {
175                     this.countDown(time, obj);
176                 }.bind(this), 500);
177                 return;
178             }
179
180             obj.text(time);
181             if (time > 0) {
182                 if (this.nfc.isPowered()) {
183                     time -= 1;
184                     this.timeOutHandler = setTimeout(function () {
185                         this.countDown(time, obj);
186                     }.bind(this), 1000);
187                 } else {
188                     this.nfc.timeExpired();
189                 }
190             } else {
191                 this.nfc.timeExpired();
192             }
193         },
194
195         saveContact: function saveContact() {
196             var contact = null,
197                 data = $('#contact').data('contactsData');
198             if (!(data.phone && (data.first || data.last))) {
199                 this.ui.moveToStartPage('Cannot add empty contact');
200                 console.error('saveContact error: empty contact');
201             } else {
202                 try {
203                     contact = new tizen.Contact(data.vCard, 'VCARD_30');
204                     this.addressBook.add(contact);
205                     this.ui.moveToStartPage('New contact added');
206                 } catch (err) {
207                     this.ui.moveToStartPage('Problem with new contact adding');
208                     console.error('saveContact error:' + err.name);
209                 }
210             }
211         },
212
213         /**
214          * Load contacts from the address book and pass the result to a callback
215          *
216          * @param {function} successCallback
217          * @param {function} errorCallback
218          */
219         loadContacts: function loadContacts(successCallback, errorCallback) {
220             this.addressBook.find(successCallback, errorCallback);
221         }
222
223     };
224
225 }());
226
227 app = new App();
228
229 $(document).ready(app.init.bind(app));