Tizen 2.0 Release
[samples/web/ContactsExchanger.git] / js / main.js
1 /*
2  *      Copyright 2012  Samsung Electronics Co., Ltd
3  *
4  *      Licensed under the Flora License, Version 1.0 (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://www.tizenopensource.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, timeExpired, contactList: true, moveToStartPage, stopNFC, setTagDetectRead, setTagDetectWrite, setTargetDetect, startNFC */
19
20 var nfcAdapter = null;
21 var addressBook = null;
22 var appStarted = false;
23 var timeOutHandler = null;
24 var popup = null;
25 var nfcTarget = null;
26 var nfcStateMemory = false;
27
28 var showPopup = function (message, page) {
29         "use strict";
30         popup = $('<div id="popup" data-role="popupwindow" data-style="center_basic_1btn"><p data-role="text">' + message + '</p><div data-role="button-bg"><a href="#" data-role="button" data-inline="true" onclick="closePopup();">OK</a></div></div>');
31         page.append(popup);
32         page.trigger('create');
33         popup.data('page', page);
34         popup.popupwindow('open');
35 };
36
37 var closePopup = function () {
38         "use strict";
39         var page = popup.data('page');
40         page.data('monit', '');
41         popup.popupwindow('close');
42         popup.remove();
43 };
44
45 var disableAccept = function () {
46         "use strict";
47         $('#accept-choose').css('pointer-events', 'none').addClass('ui-disabled');
48 };
49
50 var enableAccept = function () {
51         "use strict";
52         $('#accept-choose').css('pointer-events', 'auto').removeClass('ui-disabled');
53 };
54
55 var checkCharsSize = function (string) {
56         "use strict";
57         var i, result = '', length = string.length;
58         for (i = 0; i < length; i += 1) {
59                 if (string.charCodeAt(i) < 256) {
60                         result += string[i];
61                 }
62         }
63         return result;
64 };
65
66 var saveDefaultCard = function () {
67         "use strict";
68         var elementSelected = $('#message-chat li.selected');
69         localStorage.started = true;
70         localStorage.id = elementSelected.attr('id');
71         localStorage.firstName = checkCharsSize(elementSelected.attr('firstName'));
72         localStorage.lastName = checkCharsSize(elementSelected.attr('lastName'));
73         localStorage.phoneNumber = checkCharsSize(elementSelected.attr('phoneNumber'));
74         localStorage.vCard = elementSelected.attr('vCard');
75         $.mobile.changePage('#start');
76 };
77
78 var initAddressBook = function () {
79         "use strict";
80         var addressBooksCB = function (addressbooks) {
81                 if (addressbooks.length > 0) {
82                         addressBook =  addressbooks[0];
83                 } else {
84                         console.log('addressBook: failed');
85                 }
86         },
87                 errorCB = function (e) {
88                         console.log('problem with getAddressBooks() method: ' + e.message);
89                 };
90
91         try {
92                 tizen.contact.getAddressBooks(addressBooksCB, errorCB);
93         } catch (e) {
94                 console.log('problem with getAddressBooks() method: ' + e.message);
95         }
96 };
97
98 var createListRecord = function (contacts) {
99         "use strict";
100         contactList = contacts;
101         $.mobile.changePage('#choose');
102 };
103
104 var prepareCallerName = function (contact) {
105         "use strict";
106         var callerName, firstName, lastName;
107         callerName = '';
108         firstName = contact.name.firstName;
109         lastName = contact.name.lastName;
110         if (firstName !== '' && firstName !== null) {
111                 callerName = firstName;
112         }
113         if (lastName !== '' && lastName !== null) {
114                 if (callerName === '') {
115                         callerName += lastName;
116                 } else {
117                         callerName += ' ';
118                         callerName += lastName;
119                 }
120         }
121         if (callerName === '') {
122                 callerName = 'no name';
123         }
124         return callerName;
125 };
126
127 var showContactsList = function () {
128         "use strict";
129         var errorCB,
130                 contactsFoundCB;
131
132         contactsFoundCB = function (contacts) {
133                 var ul = $('<ul data-role="listview" id="message-chat"></ul>'),
134                         listElementTap,
135                         sortedContactList = [],
136                         i,
137                         j,
138                         len,
139                         length,
140                         firstName = '',
141                         lastName = '',
142                         phoneNumber = '',
143                         id,
144                         vCard,
145                         listElement;
146
147                 $('#choose > #content-choose > .ui-scrollview-view').empty().append(ul);
148
149                 listElementTap = function (event) {
150                         event.preventDefault();
151                         enableAccept();
152                         $(this).parent().find('li').css('background-color', '#fff').removeClass('selected');
153                         $(this).css('background-color', '#ccc').addClass('selected');
154                 };
155
156                 for (i = 0, len = contacts.length; i < len; i += 1) {
157                         firstName = '';
158                         lastName = '';
159                         phoneNumber = '';
160                         id = contacts[i].id;
161                         vCard = contacts[i].convertToString('VCARD_30');
162                         if (contacts[i].name.firstName !== null) {
163                                 firstName = contacts[i].name.firstName;
164                         }
165                         if (contacts[i].name.lastName !== null) {
166                                 lastName = contacts[i].name.lastName;
167                         }
168                         if (contacts[i].phoneNumbers[0] !== undefined) {
169                                 phoneNumber = contacts[i].phoneNumbers[0].number;
170                         }
171                         sortedContactList.push({caller: prepareCallerName(contacts[i]), firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, id: id, vCard: vCard, contact: contacts[i]});
172                 }
173
174                 sortedContactList.sort(function (a, b) {
175                         if (a.caller < b.caller) {
176                                 return -1;
177                         }
178                         if (a.caller > b.caller) {
179                                 return 1;
180                         }
181                         return 0;
182                 });
183
184                 for (j = 0, length = sortedContactList.length; j < length; j += 1) {
185                         listElement = $('<li class="ui-li-2line-2sub" firstName="' + sortedContactList[j].firstName + '" lastName="' + sortedContactList[j].lastName + '" phoneNumber="' + sortedContactList[j].phoneNumber + '" id="' + sortedContactList[j].id + '" vCard="' + sortedContactList[j].vCard + '"><span class="ui-li-text-main">' + sortedContactList[j].caller + '</span><span class="ui-li-text-sub">' + sortedContactList[j].phoneNumber + '</span></li>');
186                         if (localStorage.id === listElement.attr('id')) {
187                                 listElement.css('background-color', '#ccc');
188                         }
189                         listElement.on('tap', listElementTap);
190                         ul.append(listElement);
191                 }
192
193                 $('#choose > #content-choose').trigger('create');
194         };
195         errorCB = function (e) {
196                 console.log('problem with find() method: ' + e.message);
197         };
198         addressBook.find(contactsFoundCB, errorCB);
199 };
200
201 var countDown = function (time, obj) {
202         "use strict";
203         obj.text(time);
204         if (time > 0) {
205                 time -= 1;
206                 timeOutHandler = setTimeout(function () { countDown(time, obj); }, 1000);
207         } else {
208                 timeExpired();
209         }
210 };
211
212 var prepareWaitingPage = function (title, text) {
213         "use strict";
214         var waitingBox, waitingContent;
215         waitingBox = $('<div class="box" id="waitingBox"></div>');
216         waitingContent = $('<p class="defaultVeryBigText">' + text + '</p><p class="defaultCounterText" id="counter"></p>');
217         $('#header-transfer H1').text(title);
218         $('#content-transfer .ui-scrollview-view').empty();
219         waitingBox.append(waitingContent);
220         $('#content-transfer .ui-scrollview-view').append(waitingBox);
221         $('#content-start').trigger('create');
222         countDown(10, $('#counter'));
223 };
224
225 var loadTemporaryContent = function () {
226         "use strict";
227         var temporaryBox, temporaryContent, temporaryButton;
228         temporaryBox = $('<div class="box" id="temporaryBox"></div>');
229         temporaryContent = $('<p class="defaultText">Default card hasn\'t defined yet!<br>Do you want to define it now?</p>');
230         temporaryButton = $('<div data-role="button" class="ui-btn-create">Create default card</div>');
231
232         temporaryButton.on('tap', function (event) {
233                 event.preventDefault();
234                 $.mobile.changePage('#choose');
235         });
236
237         $('#content-start .ui-scrollview-view').empty();
238         temporaryBox.append(temporaryContent).append(temporaryButton);
239         $('#content-start .ui-scrollview-view').append(temporaryBox);
240         $('#content-start').trigger('create');
241 };
242
243 var loadStartContent = function () {
244         "use strict";
245         var startBox, gap, comment, changeContact, readFromCard, writeToCard, communicateWithOtherDevice;
246         startBox = $('<div class="box" id="startBox"></div>');
247         gap = $('<div class="gap"></div>');
248         comment = $('<div id="comment"><p class="comment">Your default contact</p><p class="comment">( ' + (localStorage.firstName || '') + ' ' + (localStorage.lastName || '') + ' )</p></div>');
249         changeContact = $('<div data-role="button" class="ui-btn-create">Change your default contact</div>');
250         changeContact.on('tap', function (event) {
251                 event.preventDefault();
252                 $.mobile.changePage('#choose');
253         });
254         readFromCard = $('<div data-role="button" class="ui-btn-create">Read from card</div>');
255         readFromCard.on('tap', function (event) {
256                 event.preventDefault();
257                 $('#transfer').data('option', 'read');
258                 $.mobile.changePage('#transfer');
259         });
260         writeToCard = $('<div data-role="button" class="ui-btn-create">Write to card</div>');
261         writeToCard.on('tap', function (event) {
262                 event.preventDefault();
263                 $('#transfer').data('option', 'write');
264                 $.mobile.changePage('#transfer');
265         });
266         communicateWithOtherDevice = $('<div data-role="button" class="ui-btn-create">Communicate with other device</div>');
267         communicateWithOtherDevice.on('tap', function (event) {
268                 event.preventDefault();
269                 $('#transfer').data('option', 'communicate');
270                 $.mobile.changePage('#transfer');
271         });
272
273         $('#content-start .ui-scrollview-view').empty();
274         startBox.append(changeContact).append(gap.clone()).append(readFromCard).append(gap.clone()).append(writeToCard).append(gap.clone()).append(communicateWithOtherDevice);
275         $('#content-start .ui-scrollview-view').append(comment);
276         $('#content-start .ui-scrollview-view').append(startBox);
277         $('#content-start').trigger('create');
278 };
279
280 var loadStartPage = function () {
281         "use strict";
282         if (localStorage.started === undefined) {
283                 loadTemporaryContent();
284         } else {
285                 loadStartContent();
286         }
287 };
288
289 var prepareContactsTemplate = function (phone, first, last) {
290         "use strict";
291         var i, ul;
292
293         ul = $('<ul data-role="listview" id="contacts-data"></ul>');
294         $('#contact > #content-contact > .ui-scrollview-view').empty().append(ul);
295
296         ul.append($('<li class="ui-li-2line-2sub"><span class="ui-li-text-main contacts-data-value">' + ((first === '' || first === 'null') ? '...' : first) + '</span><span class="ui-li-text-sub contacts-data-title">First Name</span></li>'));
297         ul.append($('<li class="ui-li-2line-2sub"><span class="ui-li-text-main contacts-data-value">' + ((last === '' || last === 'null') ? '...' : last) + '</span><span class="ui-li-text-sub contacts-data-title">Last Name</span></li>'));
298         ul.append($('<li class="ui-li-2line-2sub"><span class="ui-li-text-main contacts-data-value">' + ((phone === '' || phone === 'null') ? '...' : phone) + '</span><span class="ui-li-text-sub contacts-data-title">Phone Number</span></li>'));
299
300         $('#contact > #content-contact').trigger('create');
301 };
302
303 var saveContact = function () {
304         "use strict";
305         var phone, first, last, contactPage = $('#contact'), contact = null;
306         phone = contactPage.data('contactsData').phone;
307         first = contactPage.data('contactsData').first;
308         last = contactPage.data('contactsData').last;
309
310         try {
311                 contact = new tizen.Contact({name: new tizen.ContactName({firstName: first, lastName: last}), phoneNumbers: [new tizen.ContactPhoneNumber(phone)]});
312                 addressBook.add(contact);
313                 moveToStartPage('New contact added');
314         } catch (err) {
315                 moveToStartPage('Problem with new contact adding');
316                 console.log('The following error occurred while adding: ' + err.name);
317         }
318 };
319
320 var defineEvents = function () {
321         "use strict";
322         $('#header-start .ui-btn-back').on('tap', function (event) {
323                 event.preventDefault();
324                 stopNFC();
325         });
326
327         $('#footer-transfer').on('tap', '.ui-btn-back', function (event) {
328                 event.preventDefault();
329                 timeExpired();
330         });
331
332         $('#footer-contact').on('tap', '.ui-btn-back', function (event) {
333                 event.preventDefault();
334                 $.mobile.changePage('#start');
335         });
336
337         $('#choose').on('pagebeforeshow', function () {
338                 disableAccept();
339         });
340
341         $('#choose').on('pageshow', function (event) {
342                 showContactsList();
343         });
344
345         $('#contact').on('pageshow', function (event) {
346                 var phone, first, last;
347                 phone = $(this).data('contactsData').phone;
348                 first = $(this).data('contactsData').first;
349                 last = $(this).data('contactsData').last;
350                 prepareContactsTemplate(phone, first, last);
351         });
352
353         $('#accept-choose').on('tap', function (event) {
354                 event.preventDefault();
355                 saveDefaultCard();
356         });
357
358         $('#save-contact').on('tap', function (event) {
359                 event.preventDefault();
360                 saveContact();
361         });
362
363         $('#start').on('pagebeforeshow', function () {
364                 if (appStarted) {
365                         loadStartPage();
366                 }
367         });
368
369         $('#start').on('pageshow', function () {
370                 var monit, obj;
371                 obj = $(this);
372                 monit = obj.data('monit');
373                 if (monit !== '' && monit !== undefined) {
374                         showPopup(obj.data('monit'), obj);
375                 }
376         });
377
378         $('#transfer').on('pageshow', function () {
379                 var option = $(this).data('option');
380                 if (option === 'read') {
381                         prepareWaitingPage('Card to Device', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
382                         try {
383                                 setTagDetectRead();
384                         } catch (err) {
385                                 console.log(err);
386                         }
387                 } else if (option === 'write') {
388                         prepareWaitingPage('Device to Card', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
389                         try {
390                                 setTagDetectWrite();
391                         } catch (er) {
392                                 console.log(er);
393                         }
394                 } else {
395                         prepareWaitingPage('Device to Device', 'PUT YOUR DEVICE<br>CLOSE TO<br>OTHER DEVICE');
396                         try {
397                                 setTargetDetect();
398                         } catch (e) {
399                                 console.log(e);
400                         }
401                 }
402         });
403 };
404
405 var init = function () {
406         "use strict";
407         defineEvents();
408         initAddressBook();
409         startNFC();
410 };
411
412 $(document).ready(init);