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