application sources from tizen_2.2
[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 */
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.lastName = elementSelected.data('lastName');
58                         localStorage.phoneNumber = elementSelected.data('phoneNumber');
59                         localStorage.vCard = elementSelected.data('vCard');
60                         this.started = true;
61                         $.mobile.changePage('#start');
62                 },
63
64                 updateDefaultCard: function updateDefaultCard (contact) {
65                         localStorage.caller =  this.ui.prepareCallerName(contact);
66                         localStorage.firstName = contact.name.firstName || '';
67                         localStorage.lastName = contact.name.lastName || '';
68                         localStorage.phoneNumber =  contact.phoneNumbers[0].number;
69                         localStorage.id = contact.id;
70                         localStorage.vCard = contact.convertToString('VCARD_30');
71                 },
72
73                 /**
74                  * @param {Array} addressbooks
75                  */
76                 getAddressBooksSuccess: function getAddressBooksSuccess(addressbooks) {
77                         if (addressbooks.length > 0) {
78                                 var self = this,
79                                 resetLocalSorage = function () {
80                                         // Reset localStorage
81                                         localStorage.clear();
82                                         self.started = false;
83
84                                         // Load start page with temporary content
85                                         self.ui.moveToStartPage();
86                                         self.ui.loadTemporaryContent();
87                                 };
88                                 this.addressBook =  addressbooks[0];
89
90                                 if (localStorage.id) {
91                                         try {
92                                                 this.updateDefaultCard(
93                                                         this.addressBook.get(localStorage.id)
94                                                 );
95                                         } catch (err) {
96                                                 if (err.name === "NotFoundError") {
97                                                         resetLocalSorage();
98                                                 }
99                                         }
100                                 }
101
102                                 // Registers to be notified when the address book changes
103                                 this.addressBook.addChangeListener({
104                                                 oncontactsadded: function(contacts) {
105                                                         // Refresh if choose page active
106                                                         self.ui.refreshIfActivePage("choose");
107                                                 },
108                                                 oncontactsremoved: function(ids) {
109                                                         // Refresh localStorage if default contact was deleted
110                                                         if (ids.indexOf(localStorage.id) >= 0) {
111                                                                 resetLocalSorage();
112                                                                 alert("Your default contact has been removed. Please choose another one.");
113                                                         } else {
114                                                                 // Refresh if choose page active
115                                                                 self.ui.refreshIfActivePage("choose");
116                                                         }
117                                                 },
118                                                 oncontactsupdated: function (contacts) {
119                                                         var index = contacts.length;
120
121                                                         // check if default contact was updated
122                                                         while (index--) {
123                                                                 if (contacts[index].id === localStorage.id) {
124                                                                         self.updateDefaultCard(contacts[index]);
125                                                                         break;
126                                                                 }
127                                                         }
128
129                                                         self.ui.refreshIfActivePage("start");
130                                                 }
131                                 });
132                         } else {
133                                 console.error('initAddressBook failed');
134                         }
135                 },
136
137                 /**
138                  *
139                  * @param {Error} e
140                  */
141                 getAddressBooksError: function getAddressBooksError(e) {
142                         console.error('getAddressBooks() error: ' + e.message);
143                 },
144
145                 initAddressBook: function initAddressBook(callback) {
146                         try {
147                                 tizen.contact.getAddressBooks(
148                                         function (addressbook) {
149                                                 this.getAddressBooksSuccess(addressbook)
150                                                 callback();
151                                         }.bind(this),
152                                         this.getAddressBooksError.bind(this)
153                                 );
154                         } catch (e) {
155                                 if (e.name === "SecurityError") {
156                                         this.ui.showPopupWarning();
157                                 }
158                                 console.error('getAddressBooks() error: ' + e.message);
159                         }
160                 },
161
162                 countDown: function countDown(time, obj) {
163                         if (!this.counterState) {
164                                 setTimeout(function () {
165                                         this.countDown(time, obj);
166                                 }.bind(this), 500);
167                                 return;
168                         }
169
170                         obj.text(time);
171                         if (time > 0) {
172                                 if (this.nfc.isPowered()) {
173                                         time -= 1;
174                                         this.timeOutHandler = setTimeout(function () {
175                                                 this.countDown(time, obj);
176                                         }.bind(this), 1000);
177                                 } else {
178                                         this.nfc.timeExpired();
179                                 }
180                         } else {
181                                 this.nfc.timeExpired();
182                         }
183                 },
184
185                 saveContact: function saveContact() {
186                         var contact = null, i, empty = true,
187                                 data = $('#contact').data('contactsData');
188
189                         for (i in data) {
190                                 if (data.hasOwnProperty(i) && empty) {
191                                         if (data[i] !== '') {
192                                                 empty = false;
193                                         }
194                                 }
195                         }
196
197                         if (empty) {
198                                 this.ui.moveToStartPage('Cannot add empty contact');
199                                 console.error('saveContact error: empty contact');
200                         } else {
201                                 try {
202                                         contact = new tizen.Contact({
203                                                 name: new tizen.ContactName({
204                                                         caller: data.caller,
205                                                         firstName: data.first,
206                                                         lastName: data.last
207                                                 }),
208                                                 phoneNumbers: [new tizen.ContactPhoneNumber(data.phone)]
209                                         });
210                                         this.addressBook.add(contact);
211                                         this.ui.moveToStartPage('New contact added');
212                                 } catch (err) {
213                                         this.ui.moveToStartPage('Problem with new contact adding');
214                                         console.error('saveContact error:' + err.name);
215                                 }
216                         }
217                 },
218
219                 /**
220                  * Load contacts from the address book and pass the result to a callback
221                  *
222                  * @param {function} successCallback
223                  * @param {function} errorCallback
224                  */
225                 loadContacts: function loadContacts(successCallback, errorCallback) {
226                         this.addressBook.find(successCallback, errorCallback);
227                 }
228
229         };
230
231 }());
232
233 app = new App();
234
235 $(document).ready(app.init.bind(app));