[ContactsExchanger]Updated Private -> RSA
[samples/web/ContactsExchanger.git] / js / app.ui.js
1 /*jslint devel: true*/
2 /*global $, tizen, App, app, localStorage: true, TemplateManager, document, window, setTimeout */
3
4 App.Ui = null;
5
6 (function () { // strict mode wrapper
7         'use strict';
8
9         App.Ui = function App_Ui(app) {
10                 this.app = app;
11                 this.templateManager = new TemplateManager(app.config);
12         };
13
14         App.Ui.prototype = {
15                 popup: null,
16
17                 prepareCallerName: function ui_prepareCallerName(contact) {
18                         var callerName, firstName, lastName;
19
20                         callerName = '';
21                         firstName = contact.name.firstName;
22                         lastName = contact.name.lastName;
23
24                         if (firstName !== '' && firstName !== null) {
25                                 callerName = firstName;
26                         }
27                         if (lastName !== '' && lastName !== null) {
28                                 if (callerName !== '') {
29                                         callerName += ' ';
30                                 }
31                                 callerName += lastName;
32                         }
33                         if (callerName === '') {
34                                 callerName = 'No Name';
35                         }
36                         return callerName;
37                 },
38
39                 /**
40                  *
41                  * @param {string} message
42                  * @param {string} onclick
43                  * @returns {string}
44                  */
45                 getPopupHtml: function ui_getPopupHtml(message, onclick) {
46                         var html = '<div id="popup" data-role="popupwindow"'
47                                 + ' data-style="center_basic_1btn">'
48                                 + '<p data-role="text">' + message + '</p>'
49                                 + '<div data-role="button-bg">'
50                                 + '<a href="#" data-role="button" data-inline="true"'
51                                 + ' onclick="' + onclick + '">OK</a>'
52                                 + '</div>'
53                                 + '</div>';
54                         return html;
55                 },
56
57                 /**
58                  * Show a popup
59                  * @param {string} message
60                  * @param {jQuery} page
61                  */
62                 showPopup: function ui_showPopup(message, page) {
63                         this.popup = $(this.getPopupHtml(message, "app.ui.closePopup();"));
64                         page.append(this.popup);
65                         page.trigger('create');
66                         this.popup.data('page', page);
67                         this.popup.popupwindow('open');
68                 },
69
70                 closePopup: function ui_closePopup() {
71                         var page = this.popup.data('page');
72                         page.data('monit', '');
73                         this.popup.popupwindow('close');
74                         this.popup.remove();
75                         this.popup = null;
76                 },
77
78                 createListRecord: function ui_createListRecord() {
79                         $.mobile.changePage('#choose');
80                 },
81
82                 /**
83                  *
84                  * @param {string} text
85                  * @returns {string}
86                  */
87                 getWaitingContentHtml: function getWaitingContentHtml(text) {
88                         var html;
89                         html += '<p class="defaultVeryBigText">';
90                         html += text;
91                         html += '</p>';
92
93                         html += '<p class="defaultCounterText" id="counter"></p>';
94
95                         return html;
96                 },
97
98                 /**
99                  *
100                  * @param {string} title
101                  * @param {string} text
102                  */
103                 prepareWaitingPage: function ui_prepareWaitingPage(title, text) {
104                         var waitingBox, waitingContent,
105                                 contentTransfer = $('#content-transfer');
106                         waitingBox = $('<div class="box" id="waitingBox"></div>');
107                         waitingContent = $(this.getWaitingContentHtml(text));
108                         $('#header-transfer H1').text(title);
109                         contentTransfer.empty();
110                         waitingBox.append(waitingContent);
111                         contentTransfer.append(waitingBox);
112                         $('#content-start').trigger('create');
113                         this.app.countDown(10, $('#counter'));
114                         this.verticalCenter($('#waitingBox'));
115                         $('#waitingBox').show();
116                 },
117
118                 /**
119                  * @returns {string}
120                  */
121                 getTemporaryBoxHtml: function ui_getTemporaryBoxHtml() {
122                         return '<div class="box" id="temporaryBox"></div>';
123                 },
124
125                 /**
126                  * @returns {string}
127                  */
128                 getTemporaryBoxContentHtml: function ui_getTemporaryBoxContentHtml() {
129                         return '<p class="defaultText">'
130                                 + 'Default card is not defined yet!<br/>'
131                                 + 'Do you want to define it now?'
132                                 + '</p>';
133                 },
134
135                 loadTemporaryContent: function ui_loadTemporaryContent() {
136                         var temporaryBox, temporaryContent, temporaryButton;
137
138                         temporaryBox = $(this.getTemporaryBoxHtml());
139                         temporaryContent = $(this.getTemporaryBoxContentHtml());
140                         temporaryButton = $(this.getButtonHtml('Create default card'));
141
142                         temporaryButton.on('tap', function (event) {
143                                 event.preventDefault();
144                                 $.mobile.changePage('#choose');
145                         });
146
147                         temporaryBox.append(temporaryContent).append(temporaryButton);
148
149                         $('#content-start').empty().append(temporaryBox).trigger('create');
150                 },
151                 /**
152                  *
153                  * @param {string} text button text
154                  * @returns {string}
155                  */
156                 getButtonHtml: function ui_getButtonHtml(text) {
157                         return '<div data-role="button" class="ui-btn-create">'
158                                 + text
159                                 + '</div>';
160                 },
161
162                 /**
163                  *
164                  * @param {string} firstName
165                  * @param {string} lastName
166                  * @returns {string}
167                  */
168                 getCommentHtml: function ui_getCommentHtml(data) {
169                         return '<div id="comment">'
170                                 + '<p class="comment">Your default contact</p>'
171                                 + '<p class="comment" id="comment-name">'
172                                 + data.caller + '</p>'
173                                 + '<p class="comment" id="comment-phone">'
174                                 + data.phoneNumber + '</p>'
175                                 + '</div>';
176                 },
177
178                 /**
179                  * Change Contact button action
180                  * @event
181                  * @param {Event} event
182                  */
183                 changeContact: function ui_changeContact(event) {
184                         event.preventDefault();
185                         $.mobile.changePage('#choose');
186                 },
187
188                 /**
189                  * @returns {jQuery}
190                  */
191                 getChangeContactButton: function ui_getChangeContactButton() {
192                         var changeContactButton;
193                         changeContactButton = $(this.getButtonHtml('Change your default contact'));
194                         changeContactButton.on('tap', this.changeContact);
195                         return changeContactButton;
196                 },
197
198                 /**
199                  * Read From Card button action
200                  * @event
201                  * @param {Event} event
202                  */
203                 readFromCard: function ui_readFromCard(event) {
204                         event.preventDefault();
205                         if (tizen.nfc.getDefaultAdapter().powered) {
206                                 try {
207                                         $('#transfer').data('option', 'read');
208                                         $.mobile.changePage('#transfer');
209                                 } catch (e) {
210                                         console.error(e.message);
211                                 }
212                         } else {
213                                 $.mobile.changePage('#start');
214                                 alert('Please turn on NFC adapter');
215                         }
216                 },
217
218                 /**
219                  * @returns {jQuery}
220                  */
221                 getReadFromCardButton: function ui_getReadFromCardButton() {
222                         var readFromCardButton;
223                         readFromCardButton = $(this.getButtonHtml('Read from card'));
224                         readFromCardButton.on('tap', this.readFromCard);
225                         return readFromCardButton;
226                 },
227
228                 /**
229                  * Write To Card button action
230                  * @param {Event} event
231                  */
232                 writeToCard: function ui_writeToCard(event) {
233                         event.preventDefault();
234                         if (tizen.nfc.getDefaultAdapter().powered) {
235                                 try {
236                                         $('#transfer').data('option', 'write');
237                                         $.mobile.changePage('#transfer');
238                                 } catch (e) {
239                                         console.error(e.message);
240                                 }
241                         } else {
242                                 alert('Please turn on NFC adapter');
243                         }
244                 },
245
246                 /**
247                  * @returns {jQuery}
248                  */
249                 getWriteToCardButton: function ui_getWriteToCardButton() {
250                         var writeToCardButton;
251                         writeToCardButton = $(this.getButtonHtml('Write to card'));
252                         writeToCardButton.on('tap', this.writeToCard);
253                         return writeToCardButton;
254                 },
255
256                 /**
257                  * Communicate With Other Device button action
258                  * @param {type} event
259                  */
260                 communicateWithOtherDevice: function ui_communicateWithOtherDevice(event) {
261                         event.preventDefault();
262                         if (tizen.nfc.getDefaultAdapter().powered) {
263                                 try {
264                                         $('#transfer').data('option', 'communicate');
265                                         $.mobile.changePage('#transfer');
266                                 } catch (e) {
267                                         console.error(e.message);
268                                 }
269                         } else {
270                                 alert('Please turn on NFC adapter');
271                         }
272                 },
273
274                 /**
275                  * @returns {jQuery}
276                  */
277                 getCommunicateWithOtherDeviceButton: function ui_getCommunicateWithOtherDeviceButton() {
278                         var communicateWithOtherDeviceButton;
279                         communicateWithOtherDeviceButton = $(this.getButtonHtml('Communicate with another device'));
280                         communicateWithOtherDeviceButton.on('tap', this.communicateWithOtherDevice);
281                         return communicateWithOtherDeviceButton;
282                 },
283
284                 loadStartContent: function ui_loadStartContent() {
285                         var startBox, contentStart, gap, comment;
286                         contentStart = $('#content-start');
287                         startBox = $('<div class="box" id="startBox"></div>');
288                         gap = $('<div class="gap"></div>');
289                         comment = $(this.getCommentHtml(localStorage));
290
291                         contentStart.empty();
292                         startBox
293                                 .append(this.getChangeContactButton())
294                                 .append(gap.clone())
295                                 .append(this.getReadFromCardButton())
296                                 .append(gap.clone())
297                                 .append(this.getWriteToCardButton())
298                                 .append(gap.clone())
299                                 .append(this.getCommunicateWithOtherDeviceButton())
300                                 .prepend(comment);
301
302                         contentStart.append(startBox);
303                         contentStart.trigger('create');
304                 },
305
306                 loadStartPage: function ui_loadStartPage() {
307                         if (localStorage.started === undefined) {
308                                 this.loadTemporaryContent();
309                         } else {
310                                 this.loadStartContent();
311                         }
312                         $.mobile.activePage.page('refresh');
313                 },
314
315                 /**
316                  *
317                  * @param {string} value
318                  * @param {string} label
319                  * @returns {string}
320                  */
321                 getLiHtml: function ui_getLiHtml(value, label) {
322                         var html;
323                         html = '<li class="ui-li-multiline">'
324                                 + '<a href="#">'
325                                 + ((value === '' || value === 'null') ? '...' : value)
326                                 + '<span class="ui-li-text-sub">' + label + '</span>'
327                                 + '</a>'
328                                 + '</li>';
329                         return html;
330                 },
331
332                 /**
333                  *
334                  * @param {string} phone
335                  * @param {string} first
336                  * @param {string} last
337                  * @returns {string}
338                  */
339                 getContactsUlHtml: function ui_getContactsUlHtml(phone, first, last) {
340                         var html;
341                         html = '<ul data-role="listview" id="contacts-data">';
342                         html += this.getLiHtml(first, 'First Name');
343                         html += this.getLiHtml(last, 'Last Name');
344                         html += this.getLiHtml(phone, 'Phone');
345                         html += '</ul>';
346                         return html;
347                 },
348
349                 /**
350                  * @param {object} contact
351                  * @returns {string}
352                  */
353                 getContactsListElement: function ui_getContactsListElement(contact) {
354                         var html =
355                                         '<li class="ui-li-multiline">'
356                                         + '<a href="#">' + contact.caller
357                                         + '<span class="ui-li-text-sub">' +
358                                         contact.phoneNumber
359                                         + '</span>'
360                                         + '</a>'
361                                         + '</li>';
362                         return html;
363                 },
364
365                 prepareContactsTemplate: function ui_prepareContactsTemplate(phone, first, last) {
366                         $('#content-contact > .ui-scrollview-view')
367                                 .empty()
368                                 .append(this.getContactsUlHtml(phone, first, last));
369                         $('#content-contact').trigger('create');
370                 },
371
372                 contactsCompare: function ui_contactsCompare(a, b) {
373                         if (a.caller < b.caller) {
374                                 return -1;
375                         }
376                         if (a.caller > b.caller) {
377                                 return 1;
378                         }
379                         return 0;
380                 },
381
382                 createSortedContactArray: function ui_createSortedContactArray(contacts) {
383                         var i, len, sortedContactList = [], contact, phoneNumber;
384
385                         for (i = 0, len = contacts.length; i < len; i += 1) {
386                                 contact = contacts[i];
387                                 if (contact.phoneNumbers.length === 0) {
388                                         phoneNumber = '';
389                                 } else {
390                                         phoneNumber = contact.phoneNumbers[0].number;
391                                 }
392                                 sortedContactList.push({
393                                         caller: this.prepareCallerName(contact),
394                                         firstName: contact.name.firstName || '',
395                                         lastName: contact.name.lastName || '',
396                                         phoneNumber: phoneNumber,
397                                         id: contact.id,
398                                         vCard: contact.convertToString('VCARD_30'),
399                                         contact: contact
400                                 });
401                         }
402                         sortedContactList.sort(this.contactsSort);
403
404                         return sortedContactList;
405                 },
406
407                 createSortedContactList: function ui_createSortedContactList(contacts) {
408                         var sortedContactList = this.createSortedContactArray(contacts),
409                                 ul = $('<ul data-role="listview" id="list-choose"></ul>'),
410                                 i,
411                                 len,
412                                 listElement,
413                                 listElementTap,
414                                 self = this,
415                                 contact;
416
417                         listElementTap = function (event) {
418                                 event.preventDefault();
419                                 $(this).addClass('selected').siblings().removeClass('selected');
420                                 self.app.saveDefaultCard();
421                         };
422
423                         for (i = 0, len = sortedContactList.length; i < len; i += 1) {
424                                 contact = sortedContactList[i];
425                                 if (contact.phoneNumber !== '') {
426                                         listElement = $(this.getContactsListElement(contact));
427                                         listElement
428                                                 .data('caller', contact.caller)
429                                                 .data('firstName', contact.firstName)
430                                                 .data('lastName', contact.lastName)
431                                                 .data('phoneNumber', contact.phoneNumber)
432                                                 .data('id', contact.id)
433                                                 .data('vCard', contact.vCard);
434                                         if (localStorage.id === listElement.data('id')) {
435                                                 listElement.addClass('selected');
436                                         }
437                                         ul.append(listElement);
438                                 }
439                         }
440                         ul.on('tap taphold', 'li', listElementTap);
441                         return ul;
442                 },
443
444                 showContactsList: function ui_showContactsList(contacts) {
445                         var ul = this.createSortedContactList(contacts);
446                         $('#content-choose > .ui-scrollview-view').empty().append(ul);
447                         $('#content-choose').trigger('create');
448                 },
449
450                 moveToStartPage: function ui_moveToStartPage(monit) {
451                         $('#start').data('monit', monit || '');
452                         $.mobile.changePage('#start');
453                 },
454
455                 isActivePage: function ui_isActivePage(id) {
456                          return (id === $.mobile.activePage.attr("id"));
457                 },
458
459                 refreshIfActivePage: function ui_refreshIfActivePage(id) {
460                         if (this.isActivePage(id)) {
461                                 $.mobile.activePage.trigger("pageshow");
462                         }
463                 },
464
465                 moveToContactPage: function ui_moveToContactPage(obj) {
466                         $('#start').data('monit', '');
467                         $('#contact').data('contactsData', obj);
468                         $.mobile.changePage('#contact');
469                 },
470
471                 disableSelections: function ui_disableSelections() {
472                         $.mobile.tizen.disableSelection(document);
473                 },
474
475                 verticalCenter: function (obj) {
476                         var marginTop = ($(window).height()
477                                 - $('[data-role=header]:visible').height()
478                                 - $('[data-role=footer]:visible').height()
479                                 - obj.outerHeight())/2;
480                         if (parseInt(obj.css('margin-top'), 10) !== marginTop) {
481                                 obj.hide().css('margin-top', marginTop).show();
482                         }
483                 },
484
485                 defineEvents: function ui_defineEvents() {
486                         var self = this;
487
488                         $('#header-start .ui-btn-back').on('tap', function (event) {
489                                 event.preventDefault();
490                                 self.app.nfc.stopNFC();
491                         });
492
493                         $('#header-start').on('click', '.ui-btn-back.ui-focus', function () {
494                                 return false;
495                         });
496
497                         $('#footer-contact').on('tap', '.ui-btn-back', function (event) {
498                                 event.preventDefault();
499                                 $.mobile.changePage('#start');
500                         });
501
502                         $('#footer-choose').on('tap', '.ui-btn-back', function (event) {
503                                 event.preventDefault();
504                                 $.mobile.changePage('#start');
505                         });
506
507                         $('#choose').on('pageshow', function (event) {
508                                 self.app.loadContacts(self.showContactsList.bind(self), function (e) {
509                                         alert('Cannot load the contacts list: ' + e.message);
510                                         console.error(e.message, e);
511                                 });
512                         });
513
514                         $('#contact').on('pageshow', function (event) {
515                                 var data = $(this).data('contactsData');
516                                 self.prepareContactsTemplate(data.phone, data.first, data.last);
517                         });
518
519                         $('#save-contact').on('tap', function (event) {
520                                 event.preventDefault();
521                                 self.app.saveContact();
522                         });
523
524                         $('#start').on('pagebeforeshow', function () {
525                                 if (self.app.started) {
526                                         self.loadStartPage();
527                                 }
528                         });
529
530                         $('#start').on('pageshow', function () {
531                                 var obj = $(this), monit = obj.data('monit');
532                                 if (monit !== '' && monit !== undefined) {
533                                         self.showPopup(obj.data('monit'), obj);
534                                 }
535                                 self.verticalCenter($('#startBox'));
536                         });
537
538                         $('#start').one('pageshow', function () {
539                                 setTimeout(function () {
540                                         self.verticalCenter($('#startBox'));
541                                 }, 20);
542                         });
543
544                         document.addEventListener('tizenhwkey', function(e) {
545                                 if (e.keyName == "back") {
546                                         if ($.mobile.activePage.attr('id') === 'start') {
547                                                 tizen.application.getCurrentApplication().exit();
548                                         } else {
549                                                 self.app.nfc.timeExpired();
550                                         }
551                                 }
552                         });
553
554                         $('#transfer').on('pageshow', function () {
555                                 if (tizen.nfc.getDefaultAdapter().powered) {
556                                         try {
557                                                 var option = $(this).data('option');
558                                                 if (option === 'read') {
559                                                         self.prepareWaitingPage('Card to device', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
560                                                         self.app.nfc.card.setTagDetectRead();
561                                                 } else if (option === 'write') {
562                                                         self.prepareWaitingPage('Device to card', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
563                                                         self.app.nfc.card.setTagDetectWrite();
564                                                 } else {
565                                                         self.prepareWaitingPage('Device to device', 'PUT YOUR DEVICE<br>CLOSE TO<br>OTHER DEVICE');
566                                                         self.app.nfc.peer.setTargetDetect();
567                                                 }
568                                         } catch (e) {
569                                                 console.error(e.message);
570                                         }
571                                 } else {
572                                         $.mobile.changePage('#start');
573                                         alert('Please turn on NFC adapter');
574                                 }
575                         });
576                 }
577
578         };
579
580 }());