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                         $('#waitingBox').css("display", "table-cell");
114                         this.app.countDown(10, $('#counter'));
115                 },
116
117                 /**
118                  * @returns {string}
119                  */
120                 getTemporaryBoxHtml: function ui_getTemporaryBoxHtml() {
121                         return '<div class="box" id="temporaryBox"></div>';
122                 },
123
124                 /**
125                  * @returns {string}
126                  */
127                 getTemporaryBoxContentHtml: function ui_getTemporaryBoxContentHtml() {
128                         return '<p class="defaultText">'
129                                 + 'Default card is not defined yet!<br/>'
130                                 + 'Do you want to define it now?'
131                                 + '</p>';
132                 },
133
134                 loadTemporaryContent: function ui_loadTemporaryContent() {
135                         var temporaryBox, temporaryContent, temporaryButton;
136
137                         temporaryBox = $(this.getTemporaryBoxHtml());
138                         temporaryContent = $(this.getTemporaryBoxContentHtml());
139                         temporaryButton = $(this.getButtonHtml('Create default card'));
140
141                         temporaryButton.on('tap', function (event) {
142                                 event.preventDefault();
143                                 $.mobile.changePage('#choose');
144                         });
145
146                         temporaryBox.append(temporaryContent).append(temporaryButton);
147
148                         $('#content-start').empty().append(temporaryBox).trigger('create');
149                 },
150                 /**
151                  *
152                  * @param {string} text button text
153                  * @returns {string}
154                  */
155                 getButtonHtml: function ui_getButtonHtml(text) {
156                         return '<div data-role="button" class="ui-btn-create">'
157                                 + text
158                                 + '</div>';
159                 },
160
161                 /**
162                  *
163                  * @param {string} firstName
164                  * @param {string} lastName
165                  * @returns {string}
166                  */
167                 getCommentHtml: function ui_getCommentHtml(firstName, lastName) {
168                         var html = '<div id="comment">'
169                                 + '<p class="comment">Your default contact</p>'
170                                 + '<p class="comment" id="comment-name">'
171                                 + (firstName || '') + ' ' + (lastName || '')
172                                 + '</p>'
173                                 + '</div>';
174                         return html;
175                 },
176
177                 /**
178                  * Change Contact button action
179                  * @event
180                  * @param {Event} event
181                  */
182                 changeContact: function ui_changeContact(event) {
183                         event.preventDefault();
184                         $.mobile.changePage('#choose');
185                 },
186
187                 /**
188                  * @returns {jQuery}
189                  */
190                 getChangeContactButton: function ui_getChangeContactButton() {
191                         var changeContactButton;
192                         changeContactButton = $(this.getButtonHtml('Change your default contact'));
193                         changeContactButton.on('tap', this.changeContact);
194                         return changeContactButton;
195                 },
196
197                 /**
198                  * Read From Card button action
199                  * @event
200                  * @param {Event} event
201                  */
202                 readFromCard: function ui_readFromCard(event) {
203                         event.preventDefault();
204                         if (tizen.nfc.getDefaultAdapter().powered) {
205                                 try {
206                                         $('#transfer').data('option', 'read');
207                                         $.mobile.changePage('#transfer');
208                                 } catch (e) {
209                                         console.error(e.message);
210                                 }
211                         } else {
212                                 $.mobile.changePage('#start');
213                                 alert('Please turn on NFC adapter');
214                         }
215                 },
216
217                 /**
218                  * @returns {jQuery}
219                  */
220                 getReadFromCardButton: function ui_getReadFromCardButton() {
221                         var readFromCardButton;
222                         readFromCardButton = $(this.getButtonHtml('Read from card'));
223                         readFromCardButton.on('tap', this.readFromCard);
224                         return readFromCardButton;
225                 },
226
227                 /**
228                  * Write To Card button action
229                  * @param {Event} event
230                  */
231                 writeToCard: function ui_writeToCard(event) {
232                         event.preventDefault();
233                         if (tizen.nfc.getDefaultAdapter().powered) {
234                                 try {
235                                         $('#transfer').data('option', 'write');
236                                         $.mobile.changePage('#transfer');
237                                 } catch (e) {
238                                         console.error(e.message);
239                                 }
240                         } else {
241                                 alert('Please turn on NFC adapter');
242                         }
243                 },
244
245                 /**
246                  * @returns {jQuery}
247                  */
248                 getWriteToCardButton: function ui_getWriteToCardButton() {
249                         var writeToCardButton;
250                         writeToCardButton = $(this.getButtonHtml('Write to card'));
251                         writeToCardButton.on('tap', this.writeToCard);
252                         return writeToCardButton;
253                 },
254
255                 /**
256                  * Communicate With Other Device button action
257                  * @param {type} event
258                  */
259                 communicateWithOtherDevice: function ui_communicateWithOtherDevice(event) {
260                         event.preventDefault();
261                         if (tizen.nfc.getDefaultAdapter().powered) {
262                                 try {
263                                         $('#transfer').data('option', 'communicate');
264                                         $.mobile.changePage('#transfer');
265                                 } catch (e) {
266                                         console.error(e.message);
267                                 }
268                         } else {
269                                 alert('Please turn on NFC adapter');
270                         }
271                 },
272
273                 /**
274                  * @returns {jQuery}
275                  */
276                 getCommunicateWithOtherDeviceButton: function ui_getCommunicateWithOtherDeviceButton() {
277                         var communicateWithOtherDeviceButton;
278                         communicateWithOtherDeviceButton = $(this.getButtonHtml('Communicate with another device'));
279                         communicateWithOtherDeviceButton.on('tap', this.communicateWithOtherDevice);
280                         return communicateWithOtherDeviceButton;
281                 },
282
283                 loadStartContent: function ui_loadStartContent() {
284                         var startBox, contentStart, gap, comment;
285                         contentStart = $('#content-start');
286                         startBox = $('<div class="box" id="startBox"></div>');
287                         gap = $('<div class="gap"></div>');
288                         comment = $(this.getCommentHtml(localStorage.firstName, localStorage.lastName));
289
290                         contentStart.empty();
291                         startBox
292                                 .append(this.getChangeContactButton())
293                                 .append(gap.clone())
294                                 .append(this.getReadFromCardButton())
295                                 .append(gap.clone())
296                                 .append(this.getWriteToCardButton())
297                                 .append(gap.clone())
298                                 .append(this.getCommunicateWithOtherDeviceButton())
299                                 .prepend(comment);
300
301                         contentStart.append(startBox);
302                         contentStart.trigger('create');
303                 },
304
305                 loadStartPage: function ui_loadStartPage() {
306                         if (localStorage.started === undefined) {
307                                 this.loadTemporaryContent();
308                         } else {
309                                 this.loadStartContent();
310                         }
311                 },
312
313                 /**
314                  *
315                  * @param {string} value
316                  * @param {string} label
317                  * @returns {string}
318                  */
319                 getLiHtml: function ui_getLiHtml(value, label) {
320                         var html;
321                         html = '<li class="ui-li-multiline">'
322                                 + '<a href="#">'
323                                 + ((value === '' || value === 'null') ? '...' : value)
324                                 + '<span class="ui-li-text-sub">' + label + '</span>'
325                                 + '</a>'
326                                 + '</li>';
327                         return html;
328                 },
329
330                 /**
331                  *
332                  * @param {string} phone
333                  * @param {string} first
334                  * @param {string} last
335                  * @returns {string}
336                  */
337                 getContactsUlHtml: function ui_getContactsUlHtml(phone, first, last) {
338                         var html;
339                         html = '<ul data-role="listview" id="contacts-data">';
340                         html += this.getLiHtml(first, 'First Name');
341                         html += this.getLiHtml(last, 'Last Name');
342                         html += this.getLiHtml(phone, 'Phone');
343                         html += '</ul>';
344                         return html;
345                 },
346
347                 /**
348                  * @param {object} contact
349                  * @returns {string}
350                  */
351                 getContactsListElement: function ui_getContactsListElement(contact) {
352                         var html =
353                                         '<li class="ui-li-multiline">'
354                                         + '<a href="#">' + contact.caller
355                                         + '<span class="ui-li-text-sub">' +
356                                         contact.phoneNumber
357                                         + '</span>'
358                                         + '</a>'
359                                         + '</li>';
360                         return html;
361                 },
362
363                 prepareContactsTemplate: function ui_prepareContactsTemplate(phone, first, last) {
364                         $('#content-contact > .ui-scrollview-view')
365                                 .empty()
366                                 .append(this.getContactsUlHtml(phone, first, last));
367                         $('#content-contact').trigger('create');
368                 },
369
370                 contactsCompare: function ui_contactsCompare(a, b) {
371                         if (a.caller < b.caller) {
372                                 return -1;
373                         }
374                         if (a.caller > b.caller) {
375                                 return 1;
376                         }
377                         return 0;
378                 },
379
380                 createSortedContactArray: function ui_createSortedContactArray(contacts) {
381                         var i, len, sortedContactList = [], contact, phoneNumber;
382
383                         for (i = 0, len = contacts.length; i < len; i += 1) {
384                                 contact = contacts[i];
385                                 if (contact.phoneNumbers.length === 0) {
386                                         phoneNumber = '';
387                                 } else {
388                                         phoneNumber = contact.phoneNumbers[0].number;
389                                 }
390                                 sortedContactList.push({
391                                         caller: this.prepareCallerName(contact),
392                                         firstName: contact.name.firstName || '',
393                                         lastName: contact.name.lastName || '',
394                                         phoneNumber: phoneNumber,
395                                         id: contact.id,
396                                         vCard: contact.convertToString('VCARD_30'),
397                                         contact: contact
398                                 });
399                         }
400                         sortedContactList.sort(this.contactsSort);
401
402                         return sortedContactList;
403                 },
404
405                 createSortedContactList: function ui_createSortedContactList(contacts) {
406                         var sortedContactList = this.createSortedContactArray(contacts),
407                                 ul = $('<ul data-role="listview" id="list-choose"></ul>'),
408                                 i,
409                                 len,
410                                 listElement,
411                                 listElementTap,
412                                 self = this,
413                                 contact;
414
415                         listElementTap = function (event) {
416                                 event.preventDefault();
417                                 $(this).addClass('selected').siblings().removeClass('selected');
418                                 self.app.saveDefaultCard();
419                         };
420
421                         for (i = 0, len = sortedContactList.length; i < len; i += 1) {
422                                 contact = sortedContactList[i];
423                                 if (contact.phoneNumber !== '') {
424                                         listElement = $(this.getContactsListElement(contact));
425                                         listElement
426                                                 .data('firstName', contact.firstName)
427                                                 .data('lastName', contact.lastName)
428                                                 .data('phoneNumber', contact.phoneNumber)
429                                                 .data('id', contact.id)
430                                                 .data('vCard', contact.vCard);
431                                         if (localStorage.id === listElement.data('id')) {
432                                                 listElement.addClass('selected');
433                                         }
434                                         ul.append(listElement);
435                                 }
436                         }
437                         ul.on('tap taphold', 'li', listElementTap);
438                         return ul;
439                 },
440
441                 showContactsList: function ui_showContactsList(contacts) {
442                         var ul = this.createSortedContactList(contacts);
443                         $('#content-choose > .ui-scrollview-view').empty().append(ul);
444                         $('#content-choose').trigger('create');
445                 },
446
447                 moveToStartPage: function ui_moveToStartPage(monit) {
448                         $('#start').data('monit', monit || '');
449                         $.mobile.changePage('#start');
450                 },
451
452                 isActivePage: function ui_isActivePage(id) {
453                          return (id === $.mobile.activePage.attr("id"));
454                 },
455
456                 refreshIfActivePage: function ui_refreshIfActivePage(id) {
457                         if (this.isActivePage(id)) {
458                                 $.mobile.activePage.trigger("pageshow");
459                         }
460                 },
461
462                 moveToContactPage: function ui_moveToContactPage(obj) {
463                         $('#start').data('monit', '');
464                         $('#contact').data('contactsData', obj);
465                         $.mobile.changePage('#contact');
466                 },
467
468                 disableSelections: function ui_disableSelections() {
469                         $.mobile.tizen.disableSelection(document);
470                 },
471
472                 /**
473                  * Fix for height of the content area
474                  */
475                 fixContentHeight: function fixContentHeight() {
476                         var contentHeight = screen.availHeight - $('div[data-role="header"]').outerHeight() - $('div[data-role="footer"]').outerHeight();
477                         $('div[data-role="content"]').css('height', contentHeight);
478                 },
479
480                 defineEvents: function ui_defineEvents() {
481                         var self = this;
482
483                         $('#header-start .ui-btn-back').on('tap', function (event) {
484                                 event.preventDefault();
485                                 self.app.nfc.stopNFC();
486                         });
487
488                         $('#header-start').on('click', '.ui-btn-back.ui-focus', function () {
489                                 return false;
490                         });
491
492                         $('#footer-contact').on('tap', '.ui-btn-back', function (event) {
493                                 event.preventDefault();
494                                 $.mobile.changePage('#start');
495                         });
496
497                         $('#footer-choose').on('tap', '.ui-btn-back', function (event) {
498                                 event.preventDefault();
499                                 $.mobile.changePage('#start');
500                         });
501
502                         $('#choose').on('pageshow', function (event) {
503                                 self.app.loadContacts(self.showContactsList.bind(self), function (e) {
504                                         alert('Cannot load the contacts list: ' + e.message);
505                                         console.error(e.message, e);
506                                 });
507                         });
508
509                         $('#contact').on('pageshow', function (event) {
510                                 var data = $(this).data('contactsData');
511                                 self.prepareContactsTemplate(data.phone, data.first, data.last);
512                         });
513
514                         $('#save-contact').on('tap', function (event) {
515                                 event.preventDefault();
516                                 self.app.saveContact();
517                         });
518
519                         $('#start').on('pagebeforeshow', function () {
520                                 if (self.app.started) {
521                                         self.loadStartPage();
522                                 }
523                         });
524
525                         $('#start').on('pageshow', function () {
526                                 var obj = $(this), monit = obj.data('monit');
527                                 if (monit !== '' && monit !== undefined) {
528                                         self.showPopup(obj.data('monit'), obj);
529                                 }
530                         });
531
532                         document.addEventListener('tizenhwkey', function(e) {
533                                 if (e.keyName == "back") {
534                                         if ($.mobile.activePage.attr('id') === 'start') {
535                                                 tizen.application.getCurrentApplication().exit();
536                                         } else {
537                                                 history.back();
538                                         }
539                                 }
540                         });
541
542                         $('#transfer').on('pageshow', function () {
543                                 if (tizen.nfc.getDefaultAdapter().powered) {
544                                         try {
545                                                 var option = $(this).data('option');
546                                                 if (option === 'read') {
547                                                         self.prepareWaitingPage('Card to Device', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
548                                                         self.app.nfc.card.setTagDetectRead();
549                                                 } else if (option === 'write') {
550                                                         self.prepareWaitingPage('Device to Card', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
551                                                         self.app.nfc.card.setTagDetectWrite();
552                                                 } else {
553                                                         self.prepareWaitingPage('Device to Device', 'PUT YOUR DEVICE<br>CLOSE TO<br>OTHER DEVICE');
554                                                         self.app.nfc.peer.setTargetDetect();
555                                                 }
556                                         } catch (e) {
557                                                 console.error(e.message);
558                                         }
559                                 } else {
560                                         $.mobile.changePage('#start');
561                                         alert('Please turn on NFC adapter');
562                                 }
563                         });
564                 }
565
566         };
567
568 }());