[ContactsExchanger]update ContactsExchanger(tizen_2.1)
[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                         $('#transfer').data('option', 'communicate');
262                         $.mobile.changePage('#transfer');
263                 },
264
265                 /**
266                  * @returns {jQuery}
267                  */
268                 getCommunicateWithOtherDeviceButton: function ui_getCommunicateWithOtherDeviceButton() {
269                         var communicateWithOtherDeviceButton;
270                         communicateWithOtherDeviceButton = $(this.getButtonHtml('Communicate with another device'));
271                         communicateWithOtherDeviceButton.on('tap', this.communicateWithOtherDevice);
272                         return communicateWithOtherDeviceButton;
273                 },
274
275                 loadStartContent: function ui_loadStartContent() {
276                         var startBox, contentStart, gap, comment;
277                         contentStart = $('#content-start');
278                         startBox = $('<div class="box" id="startBox"></div>');
279                         gap = $('<div class="gap"></div>');
280                         comment = $(this.getCommentHtml(localStorage.firstName, localStorage.lastName));
281
282                         contentStart.empty();
283                         startBox
284                                 .append(this.getChangeContactButton())
285                                 .append(gap.clone())
286                                 .append(this.getReadFromCardButton())
287                                 .append(gap.clone())
288                                 .append(this.getWriteToCardButton())
289                                 .append(gap.clone())
290                                 .append(this.getCommunicateWithOtherDeviceButton())
291                                 .prepend(comment);
292
293                         contentStart.append(startBox);
294                         contentStart.trigger('create');
295                 },
296
297                 loadStartPage: function ui_loadStartPage() {
298                         if (localStorage.started === undefined) {
299                                 this.loadTemporaryContent();
300                         } else {
301                                 this.loadStartContent();
302                         }
303                 },
304
305                 /**
306                  *
307                  * @param {string} value
308                  * @param {string} label
309                  * @returns {string}
310                  */
311                 getLiHtml: function ui_getLiHtml(value, label) {
312                         var html;
313                         html = '<li class="ui-li-multiline">'
314                                 + '<a href="#">'
315                                 + ((value === '' || value === 'null') ? '...' : value)
316                                 + '<span class="ui-li-text-sub">' + label + '</span>'
317                                 + '</a>'
318                                 + '</li>';
319                         return html;
320                 },
321
322                 /**
323                  *
324                  * @param {string} phone
325                  * @param {string} first
326                  * @param {string} last
327                  * @returns {string}
328                  */
329                 getContactsUlHtml: function ui_getContactsUlHtml(phone, first, last) {
330                         var html;
331                         html = '<ul data-role="listview" id="contacts-data">';
332                         html += this.getLiHtml(first, 'First Name');
333                         html += this.getLiHtml(last, 'Last Name');
334                         html += this.getLiHtml(phone, 'Phone');
335                         html += '</ul>';
336                         return html;
337                 },
338
339                 /**
340                  * @param {object} contact
341                  * @returns {string}
342                  */
343                 getContactsListElement: function ui_getContactsListElement(contact) {
344                         var html =
345                                         '<li class="ui-li-multiline" firstName="' + contact.firstName
346                                         + '" lastName="' + contact.lastName +
347                                         '" phoneNumber="' + contact.phoneNumber +
348                                         '" id="' + contact.id +
349                                         '" vCard="' + contact.vCard + '">'
350                                         + '<a href="#">' + contact.caller
351                                         + '<span class="ui-li-text-sub">' +
352                                         contact.phoneNumber
353                                         + '</span>'
354                                         + '</a>'
355                                         + '</li>';
356                         return html;
357                 },
358
359                 prepareContactsTemplate: function ui_prepareContactsTemplate(phone, first, last) {
360                         $('#content-contact > .ui-scrollview-view')
361                                 .empty()
362                                 .append(this.getContactsUlHtml(phone, first, last));
363                         $('#content-contact').trigger('create');
364                 },
365
366                 contactsCompare: function ui_contactsCompare(a, b) {
367                         if (a.caller < b.caller) {
368                                 return -1;
369                         }
370                         if (a.caller > b.caller) {
371                                 return 1;
372                         }
373                         return 0;
374                 },
375
376                 createSortedContactArray: function ui_createSortedContactArray(contacts) {
377                         var i, len, sortedContactList = [], contact, phoneNumber;
378
379                         for (i = 0, len = contacts.length; i < len; i += 1) {
380                                 contact = contacts[i];
381                                 if (contact.phoneNumbers.length === 0) {
382                                         phoneNumber = '';
383                                 } else {
384                                         phoneNumber = contact.phoneNumbers[0].number;
385                                 }
386                                 sortedContactList.push({
387                                         caller: this.prepareCallerName(contact),
388                                         firstName: contact.name.firstName || '',
389                                         lastName: contact.name.lastName || '',
390                                         phoneNumber: phoneNumber,
391                                         id: contact.id,
392                                         vCard: contact.convertToString('VCARD_30'),
393                                         contact: contact
394                                 });
395                         }
396                         sortedContactList.sort(this.contactsSort);
397
398                         return sortedContactList;
399                 },
400
401                 createSortedContactList: function ui_createSortedContactList(contacts) {
402                         var sortedContactList = this.createSortedContactArray(contacts),
403                                 ul = $('<ul data-role="listview" id="list-choose"></ul>'),
404                                 i,
405                                 len,
406                                 listElement,
407                                 listElementTap,
408                                 self = this;
409
410                         listElementTap = function (event) {
411                                 event.preventDefault();
412                                 $(this).addClass('selected').siblings().removeClass('selected');
413                                 self.app.saveDefaultCard();
414                         };
415
416                         for (i = 0, len = sortedContactList.length; i < len; i += 1) {
417                                 listElement = $(this.getContactsListElement(sortedContactList[i]));
418                                 if (localStorage.id === listElement.attr('id')) {
419                                         listElement.addClass('selected');
420                                 }
421                                 ul.append(listElement);
422                         }
423                         ul.on('tap taphold', 'li', listElementTap);
424                         return ul;
425                 },
426
427                 showContactsList: function ui_showContactsList(contacts) {
428                         var ul = this.createSortedContactList(contacts);
429                         $('#content-choose > .ui-scrollview-view').empty().append(ul);
430                         $('#content-choose').trigger('create');
431                 },
432
433                 moveToStartPage: function ui_moveToStartPage(monit) {
434                         $('#start').data('monit', monit || '');
435                         $.mobile.changePage('#start');
436                 },
437
438                 moveToContactPage: function ui_moveToContactPage(obj) {
439                         $('#start').data('monit', '');
440                         $('#contact').data('contactsData', obj);
441                         $.mobile.changePage('#contact');
442                 },
443
444                 disableSelections: function ui_disableSelections() {
445                         $.mobile.tizen.disableSelection(document);
446                 },
447
448                 defineEvents: function ui_defineEvents() {
449                         var self = this;
450
451                         $('#header-start .ui-btn-back').on('tap', function (event) {
452                                 event.preventDefault();
453                                 self.app.nfc.stopNFC();
454                         });
455
456                         $('#footer-contact').on('tap', '.ui-btn-back', function (event) {
457                                 event.preventDefault();
458                                 $.mobile.changePage('#start');
459                         });
460
461                         $('#footer-choose').on('tap', '.ui-btn-back', function (event) {
462                                 event.preventDefault();
463                                 $.mobile.changePage('#start');
464                         });
465
466                         $('#choose').on('pageshow', function (event) {
467                                 self.app.loadContacts(self.showContactsList.bind(self), function (e) {
468                                         alert('Cannot load the contacts list: ' + e.message);
469                                         console.error(e.message, e);
470                                 });
471                         });
472
473                         $('#contact').on('pageshow', function (event) {
474                                 var data = $(this).data('contactsData');
475                                 self.prepareContactsTemplate(data.phone, data.first, data.last);
476                         });
477
478                         $('#save-contact').on('tap', function (event) {
479                                 event.preventDefault();
480                                 self.app.saveContact();
481                         });
482
483                         $('#start').on('pagebeforeshow', function () {
484                                 if (self.app.started) {
485                                         self.loadStartPage();
486                                 }
487                         });
488
489                         $('#start').on('pageshow', function () {
490                                 var monit, obj, contentStart, contentStartHeight;
491                                 obj = $(this);
492                                 monit = obj.data('monit');
493                                 if (monit !== '' && monit !== undefined) {
494                                         self.showPopup(obj.data('monit'), obj);
495                                 }
496                                 contentStart = $('#content-start');
497
498                                 if (contentStart.height() > $(window).height()) {
499                                         contentStartHeight = $(window).height() - $('#header-start').height()
500                                                 - parseInt(contentStart.css('padding-top'), 10) - parseInt(contentStart.css('padding-bottom'), 10);
501                                 } else {
502                                         contentStartHeight = contentStart.height();
503                                 }
504                                 setTimeout(function () { // workaround (setTimeout with 0 delay)
505                                         contentStart
506                                                 .css('height', contentStartHeight  + 'px')
507                                                 .css('min-height', 'auto')
508                                         obj.css('min-height', 'auto');
509                                 }, 0);
510                         });
511
512                         $('#transfer').on('pageshow', function () {
513                                 var contentTransfer = $('#content-transfer');
514                                 contentTransfer.css('width', contentTransfer.width() + 'px');
515                                 setTimeout(function () { // workaround (setTimeout with 0 delay)
516                                         contentTransfer.css('height', contentTransfer.css('min-height'));
517                                 }, 0);
518                         });
519
520                         $('#transfer').on('pageshow', function () {
521                                 if (tizen.nfc.getDefaultAdapter().powered) {
522                                         try {
523                                                 var option = $(this).data('option');
524                                                 if (option === 'read') {
525                                                         self.prepareWaitingPage('Card to Device', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
526                                                         self.app.nfc.card.setTagDetectRead();
527                                                 } else if (option === 'write') {
528                                                         self.prepareWaitingPage('Device to Card', 'PUT WIRELESS TAG<br>CLOSE TO<br>YOUR DEVICE');
529                                                         self.app.nfc.card.setTagDetectWrite();
530                                                 } else {
531                                                         self.prepareWaitingPage('Device to Device', 'PUT YOUR DEVICE<br>CLOSE TO<br>OTHER DEVICE');
532                                                         self.app.nfc.peer.setTargetDetect();
533                                                 }
534                                         } catch (e) {
535                                                 console.error(e.message);
536                                         }
537                                 } else {
538                                         $.mobile.changePage('#start');
539                                         alert('Please turn on NFC adapter');
540                                 }
541                         });
542                 }
543
544         };
545
546 }());