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