[BluetoothChat]update BluetoothChat(tizen_2.1)
authorgs86.lee <gs86.lee@samsung.com>
Fri, 12 Apr 2013 06:29:08 +0000 (15:29 +0900)
committergs86.lee <gs86.lee@samsung.com>
Fri, 12 Apr 2013 06:41:29 +0000 (15:41 +0900)
Change-Id: If18e17a9dd2490b4b404c453f4a1d82458583a87

28 files changed:
LICENSE [new file with mode: 0644]
NOTICE [new file with mode: 0644]
config.xml
css/style.css
icon.png
index.html
js/app.client.js [new file with mode: 0644]
js/app.client.model.js [new file with mode: 0644]
js/app.config.js [new file with mode: 0644]
js/app.helpers.js [new file with mode: 0644]
js/app.js [new file with mode: 0644]
js/app.model.js [new file with mode: 0644]
js/app.server.js [new file with mode: 0644]
js/app.server.model.js [new file with mode: 0644]
js/app.ui.events.js [new file with mode: 0644]
js/app.ui.js [new file with mode: 0644]
js/app.ui.templateManager.js [new file with mode: 0644]
js/client.js
js/main.js
js/server.js
templates/bye_popup.tpl [new file with mode: 0644]
templates/chat_page.tpl [new file with mode: 0644]
templates/choose_page.tpl [new file with mode: 0644]
templates/keyboard_page.tpl [new file with mode: 0644]
templates/left_bubble.tpl [new file with mode: 0644]
templates/right_bubble.tpl [new file with mode: 0644]
templates/server_row.tpl [new file with mode: 0644]
templates/visibility_popup.tpl [new file with mode: 0644]

diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..7ccb5b5
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,75 @@
+Flora License
+
+Version 1.0, May, 2012
+
+http://www.tizenopensource.org/license
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
+
+"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
+
+"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
+
+"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
+
+"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
+
+"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
+
+"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
+
+"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
+
+"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
+
+"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
+
+"Tizen Certified Platform" shall mean a software platform that complies with the standards set forth in the Compatibility Definition Document and passes the Compatibility Test Suite as defined from time to time by the Tizen Technical Steering Group and certified by the Tizen Association or its designated agent.
+
+2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work solely as incorporated into a Tizen Certified Platform, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work solely as incorporated into a Tizen Certified Platform to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof pursuant to the copyright license above, in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
+
+  1. You must give any other recipients of the Work or Derivative Works a copy of this License; and
+
+  2. You must cause any modified files to carry prominent notices stating that You changed the files; and
+
+  3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
+
+  4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Flora License to your work
+
+To apply the Flora License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Flora License, Version 1.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.tizenopensource.org/license
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
diff --git a/NOTICE b/NOTICE
new file mode 100644 (file)
index 0000000..85044e4
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,4 @@
+Copyright (c) 2012 Samsung Electronics Co., Ltd. All rights reserved.
+Except as noted, this software is licensed under Flora License, Version 1.
+Please, see the LICENSE.Flora file for Flora License terms and conditions.
+
index 30cbdf5..9c86d0e 100644 (file)
@@ -1,15 +1,14 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<widget xmlns="http://www.w3.org/ns/widgets" xmlns:tizen="http://tizen.org/ns/widgets" id="http://sample-web-application.tizen.org/bt-chat" version="2.1.0" viewmodes="maximized">
-       <tizen:application id="2PlyGQLfgh" required_version="1.0"/>
-       <conent src="index.html"/>
-       <icon src="icon.png"/>
-       <name>BluetoothChat</name>
-       <tizen:privilege name="http://tizen.org/privilege/application.launch"/>
-       <tizen:privilege name="http://tizen.org/privilege/application.read"/>
-       <tizen:privilege name="http://tizen.org/privilege/bluetooth.admin"/>
-       <tizen:privilege name="http://tizen.org/privilege/bluetooth.gap"/>
-       <tizen:privilege name="http://tizen.org/privilege/bluetooth.spp"/>
-       <tizen:privilege name="http://tizen.org/privilege/tizen"/>
-       <tizen:setting screen-orientation="portrait" context-menu="enable" background-support="enable" encryption="disable" nodisplay="false"/>
-       <tizen:setting context-menu="enable"/>
+<widget xmlns:tizen="http://tizen.org/ns/widgets" xmlns="http://www.w3.org/ns/widgets" id="http://sample-web-application.tizen.org/bt-chat" version="2.1.0" viewmodes="maximized">
+    <tizen:application id="QmwDyrmOzO.BluetoothChat" package="QmwDyrmOzO" required_version="2.1"/>
+    <content src="index.html"/>
+    <icon src="icon.png"/>
+    <name>BluetoothChat</name>
+    <tizen:privilege name="http://tizen.org/privilege/application.launch"/>
+    <tizen:privilege name="http://tizen.org/privilege/application.read"/>
+    <tizen:privilege name="http://tizen.org/privilege/bluetooth.admin"/>
+    <tizen:privilege name="http://tizen.org/privilege/bluetooth.gap"/>
+    <tizen:privilege name="http://tizen.org/privilege/bluetooth.spp"/>
+    <tizen:privilege name="http://tizen.org/privilege/tizen"/>
+    <tizen:setting screen-orientation="portrait" context-menu="disable" background-support="enable" encryption="disable" install-location="auto"/>
 </widget>
index 4d79baa..38cf2b4 100644 (file)
@@ -1,12 +1,37 @@
+.box {
+       margin: 0px;
+       padding: 0px;
+       display: table-cell;
+       vertical-align: middle;
+       height: inherit;
+       width: inherit;
+}
+
+#start-header .ui-btn-back {
+       width: 34px;
+}
+
+#chat-header .ui-btn-back {
+       width: 34px;
+}
+
+#chat-header .ui-btn-footer-down {
+       width: 58px;
+}
+
 .ui-btn-start {
-       margin: 0px auto;
-       margin-top: 10px;
-       padding: 40px 0px 0px 0px;
+       margin: 10px auto;
+       padding: 0;
        width: 90%;
-       height: 100px;
        font-size: 26px;
 }
 
+.ui-btn-start > span {
+       padding-top: 30px;
+       padding-bottom: 30px;
+}
+
+/*
 #keyboard-text {
        width: 100%;
        margin: 0px;
        border: 0px;
        border-radius: 0px;
        overflow: hidden;
-    font-size: 24px;
-    outline: none;
+       font-size: 24px;
+       outline: none;
+}
+*/
+
+#keyboard-text {
+       width: 90%;
+       margin: 16px auto;
 }
 
 #keyboard-content .ui-scrollview-view {
        padding: 0px;
+       text-align: center;
 }
 
 #start-content {
        background-color: white;
 }
 
-/*
 #keyboard-back-button {
        position: absolute;
-       left: 5px;
-       bottom: 5px;
+       right: 50px;
+       bottom: 15px;
+       width: 40px;
 }
 
 #keyboard-ok-button {
        position: absolute;
        right: 5px;
-       bottom: 5px;
+       bottom: 15px;
+       width: 40px;
 }
-*/
 
 #ui-textArea {
        position: absolute;
 
 #chat-footer {
        height: 164px;
+}
+
+#start-monit {
+       text-align: center;
        width: 100%;
-       position: absolute;
-       bottom: 0;
 }
 
-.ui-listview .ui-li-static.ui-li-bubble-left {
-       margin-right: 50px;
+#start-monit a {
+       font-size: 1.4em;
 }
 
-.ui-listview .ui-li-static.ui-li-bubble-right {
-       margin-left: 50px;
+#chat-header-type {
+       font-size: 0.5em;
+       position: absolute;
+       top: 3px;
+       left: 3px;
+       white-space: nowrap;
+       overflow: hidden !important;
+       text-overflow: ellipsis;
+       width: 90%;
 }
 
-.ui-listview span.ui-li-bubble-time {
-       margin-left: 10px;
-       font-size: 1.2rem;
+#chat-header-name {
+       font-size: 1em;
+       position: absolute;
+       top: 25px;
+       left: 3px;
+       white-space: nowrap;
+       overflow: hidden !important;
+       text-overflow: ellipsis;
+       width: 60%;
 }
 
-#start-monit {
-       text-align: center;
-       width: 100%;
+.server-row-name {
+       white-space: nowrap;
+       overflow: hidden !important;
+       text-overflow: ellipsis;
+       width: 80%;
 }
 
-#start-monit a {
-       font-size: 1.4em;
+#discovering {
+       right: 17px;
+       top: 17px;
 }
 
 .focus {}
index 983c883..33fbb63 100755 (executable)
Binary files a/icon.png and b/icon.png differ
index 0147b6e..5ce7257 100644 (file)
@@ -2,84 +2,35 @@
 <html>
 
 <head>
-    <meta charset="utf-8"/>
-    <meta name="description" content="bt-chat"/>
-    <meta name="viewport" content="width=480, user-scalable=no" />
+       <meta charset="utf-8"/>
+       <meta name="description" content="bt-chat"/>
+       <meta name="viewport" content="width=360, user-scalable=no"/>
 
-    <title>bt-chat</title>
-    <script src="/usr/share/tizen-web-ui-fw/latest/js/jquery.js"></script>
-    <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.js"></script>
-    <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.js" data-framework-theme="tizen-white" data-framework-viewport-scale="false"></script>
+       <title>BluetoothChat</title>
+       <script src="/usr/share/tizen-web-ui-fw/latest/js/jquery.min.js"></script>
+       <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw-libs.min.js"></script>
+       <script src="/usr/share/tizen-web-ui-fw/latest/js/tizen-web-ui-fw.min.js" data-framework-theme="tizen-white" data-framework-viewport-scale="false"></script>
 
-    <script type="text/javascript" src="./js/main.js"></script>
-    <script type="text/javascript" src="./js/client.js"></script>
-    <script type="text/javascript" src="./js/server.js"></script>
-    <link rel="stylesheet" type="text/css" href="./css/style.css"/>
+       <script type="text/javascript" src="./js/main.js"></script>
+       <link rel="stylesheet" type="text/css" href="./css/style.css"/>
 </head>
 
 <body>
-    <div data-role="page" id="start" data-add-back-btn="footer" data-footer-exist="true">
-        <div data-role="header" id="start-header" data-position="fixed">
-            <h1>Bt-chat</h1>
-        </div>
-
-        <div data-role="content" id="start-content">
-               <div data-role="button" class="ui-btn-start" id="serverButton" style="display: none;">Set name and start server</div>
-               <div data-role="button" class="ui-btn-start" id="clientButton" style="display: none;">Set name and join client</div>
-               <div id="start-monit">
-                       <p>... waiting for bluetooth radio ...</p>
-               </div>
-        </div>
-
-        <div data-role="footer" data-position="fixed" id="start-footer"></div>
-    </div>
-
-    <div data-role="page" id="keyboard" data-add-back-btn="none">
-        <div data-role="header" id="keyboard-header" data-position="fixed">
-            <h1></h1>
-            <a data-role="button" id="keyboard-ok-button">OK</a>
-            <a data-role="button" id="keyboard-back-button">back</a>
-        </div>
-
-        <div data-role="content" id="keyboard-content">
-               <textarea id="keyboard-text" data-role="none" maxlength="5"></textarea>
-               <!-- <div data-role="button" id="keyboard-back-button">back</div> -->
-               <!-- <div data-role="button" id="keyboard-ok-button">OK</div> -->
-        </div>
-
-        <div data-role="footer" data-position="fixed" id="keyboard-footer"></div>
-    </div>
-
-    <div data-role="page" id="chat" data-footer-Exist="false">
-        <div data-role="header" id="chat-header" data-position="fixed">
-            <h1 id="chat-title"></h1>
-            <a data-role="button" id="chat-back-button">back</a>
-        </div>
-
-        <div data-role="content" id="chat-content"></div>
-
-        <!-- <div data-role="footer" data-position="fixed" id="chat-footer"> -->
-        <div data-role="none" id="chat-footer"><!-- workaround -->
-               <div id="ui-textArea">
-               <div id="ui-textArea-text">
-                       <textarea id="text" placeholder="type new message" data-role="none"></textarea>
-               </div>
-               <div id="ui-textArea-button">
-                       <a data-role="button" id="ui-mySend">Send</a>
-                       <!-- <div data-role="none" id="ui-myCounter"><p></p></div> -->
-               </div>
-            </div>
-        </div>
-    </div>
-
-    <div data-role="page" id="choose" data-add-back-btn="footer" data-footer-exist="true">
-        <div data-role="header" id="choose-header" data-position="fixed">
-            <h1>Choose your bt-chat server</h1>
-        </div>
-
-        <div data-role="content" id="choose-content"></div>
-
-        <div data-role="footer" data-position="fixed" id="choose-footer"></div>
-    </div>
+       <div id="start" data-role="page" data-add-back-btn="header">
+               <div id="start-header" data-role="header" data-position="fixed">
+                       <h1>BLUETOOTH CHAT</h1>
+               </div>
+
+               <div id="start-content" data-role="content" data-scroll="none">
+                       <div class="box">
+                               <div data-role="button" class="ui-btn-start" id="serverButton" style="display: none;">Set name and start server</div>
+                               <div data-role="button" class="ui-btn-start" id="clientButton" style="display: none;">Set name and join client</div>
+                               <div data-role="button" class="ui-btn-start" id="turnOnButton" style="display: none;">Turn bluetooth radio on</div>
+                               <div id="start-monit" style="display: none;">
+                                       <p>... waiting for bluetooth radio ...</p>
+                               </div>
+                       </div>
+               </div>
+       </div>
 </body>
-</html>
+</html>
\ No newline at end of file
diff --git a/js/app.client.js b/js/app.client.js
new file mode 100644 (file)
index 0000000..10dd388
--- /dev/null
@@ -0,0 +1,112 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app, ClientModel */
+/**
+ * @class Client
+ */
+
+function Client(adapter, serviceUUID) {
+       'use strict';
+       this.adapter = adapter;
+       this.serviceUUID = serviceUUID;
+       this.globalSocket = null;
+       this.init();
+       this.discovering = false;
+       this.chatServerDevice = null;
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+
+       Client.prototype = {
+               /**
+                * @type clientModel
+                */
+               model: null,
+
+               /**
+                * Initialisation function
+                */
+               init: function Client_init() {
+                       this.model = new ClientModel(this);
+                       return this;
+               },
+
+               setDiscovering: function Client_setDiscovering(boolean) {
+                       this.discovering = boolean;
+                       app.ui.setDiscoveringProgress(boolean);
+               },
+
+               getDiscovering: function Client_getDiscovering() {
+                       return this.discovering;
+               },
+
+               searchServer: function Client_searchServer() {
+                       this.model.searchServer();
+               },
+
+               addDeviceToList: function Client_addDeviceToList(device) {
+                       app.ui.addDeviceToList(device);
+               },
+
+               stopServerSearching: function Client_stopServerSearching(address) {
+                       if (address !== undefined) {
+                               this.model.stopServerSearching(this.startBonding.bind(this, address, this.connectToService.bind(this)));
+                       } else {
+                               this.model.stopServerSearching();
+                       }
+               },
+
+               startBonding: function Client_startBonding(address, callback) {
+                       this.model.startBonding(address, callback);
+               },
+
+               connectToService: function Client_connectToService(device) {
+                       this.model.connectToService(device, this.serviceUUID, this.connectToServiceSuccess.bind(this, device), this.connectToServiceError.bind(this));
+               },
+
+               connectToServiceSuccess: function Client_connectToServiceSuccess(device, socket) {
+                       this.globalSocket = socket;
+                       socket.onmessage = function () {
+                               var data, recvmsg = '', i, len, messageObj;
+                               data = socket.readData();
+                               len = data.length;
+                               for (i = 0; i < len; i += 1) {
+                                       recvmsg += String.fromCharCode(data[i]);
+                               }
+                               messageObj = JSON.parse(recvmsg);
+                               app.ui.displayReceivedMessage(messageObj.name, messageObj.text, messageObj.ping, messageObj.bye);
+                       };
+                       socket.onerror = function (e) {
+                               console.error('Client onerror');
+                               socket.close();
+                       };
+                       socket.onclose = function () {
+                               this.globalSocket = null;
+                               app.setConnection(false);
+                       };
+                       app.setConnection(true);
+                       app.ui.showChatPage(device.name);
+                       this.sendPing();
+               },
+
+               connectToServiceError: function Client_connectToServiceError(error) {
+                       console.error('Client_connectToServiceError: ' + error.message);
+               },
+
+               sendPing: function Client_sendPing() {
+                       this.model.sendPing(this.adapter.name, this.globalSocket);
+               },
+
+               sendMessage: function Client_sendMessage(message, callback) {
+                       this.model.sendMessage(this.adapter.name, this.globalSocket, message, callback);
+               },
+
+               sendBye: function Client_sendBye() {
+                       this.model.sendBye(this.adapter.name, this.globalSocket);
+               },
+
+               destroyBonding: function Client_destroyBonding() {
+                       this.model.destroyBonding(this.chatServerDevice, app.restartBluetooth.bind(app), app.ui.showStartButtons);
+               }
+       };
+}());
diff --git a/js/app.client.model.js b/js/app.client.model.js
new file mode 100644 (file)
index 0000000..a891196
--- /dev/null
@@ -0,0 +1,142 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Model
+ */
+function ClientModel(parent) {
+       'use strict';
+       this.client = parent;
+       this.init();
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       ClientModel.prototype = {
+
+               /**
+                * API module initialisation
+                */
+               init: function ClientModel_init() {},
+
+               searchServer: function ClientModel_searchServer() {
+                       var discoverDevicesSuccessCallback = {
+                               onstarted: function () {
+                                       this.client.setDiscovering(true);
+                               }.bind(this),
+                               ondevicefound: function (device) {
+                                       this.client.addDeviceToList(device);
+                               }.bind(this),
+                               ondevicedisappeared: function (address) {},
+                               onfinished: function (devices) {
+                                       this.client.setDiscovering(false);
+                               }.bind(this)
+                       };
+
+                       this.client.adapter.discoverDevices(discoverDevicesSuccessCallback, function (e) { this.client.setDiscovering(false); });
+               },
+
+               stopServerSearching: function ClientModel_stopServerSearching(callback) {
+                       if (this.client.getDiscovering()) {
+                               this.client.adapter.stopDiscovery(function () {
+                                       this.client.setDiscovering(false);
+                                       if (typeof callback === 'function') {
+                                               callback();
+                                       }
+                               }.bind(this), function (e) {
+                                       console.error("Error while stopDiscovery:" + e.message);
+                               });
+                       } else if (typeof callback === 'function') {
+                               callback();
+                       }
+               },
+
+               startBonding: function ClientModel_startBonding(address, callback) {
+                       this.client.adapter.createBonding(address, function (device) { callback(device); }, function (error) { console.error('bondError: ' + error.message); });
+               },
+
+               connectToService: function ClientModel_connectToService(device, serviceUUID, successCallback, errorCallback) {
+                       this.client.chatServerDevice = device;
+                       try {
+                               device.connectToServiceByUUID(serviceUUID, successCallback, errorCallback, 'RFCOMM');
+                       } catch (error) {
+                               console.error('connectToServiceByUUID ERROR: ' + error.message);
+                       }
+               },
+
+               sendPing: function ClientModel_sendPing(name, socket) {
+                       var i, len = name.length, sendTextMsg = [];
+                       var sendTextMsg, messageObj, messageObjToString, i, len;
+                       sendTextMsg = [];
+                       messageObj = {name: encodeURIComponent(name), text: '', ping: true, bye: false};
+                       messageObjToString = JSON.stringify(messageObj);
+                       len = messageObjToString.length;
+
+                       for (i = 0; i < len; i += 1) {
+                               sendTextMsg[i] = messageObjToString.charCodeAt(i);
+                       }
+                       try {
+                               if (socket !== null && socket.state === "OPEN") {
+                                       socket.writeData(sendTextMsg);
+                               }
+                       } catch (error) {
+                               console.error('sendPing: ' + error.message);
+                       }
+               },
+
+               sendMessage: function ClientModel_sendMessage(name, socket, message, callback) {
+                       var sendTextMsg = [], messageObj, messageObjToString, i, len;
+                       name = encodeURIComponent(name);
+                       message = encodeURIComponent(message);
+                       messageObj = {name: name, text: message, ping: false, bye: false};
+                       messageObjToString = JSON.stringify(messageObj);
+                       len = messageObjToString.length;
+                       for (i = 0; i < len; i += 1) {
+                               sendTextMsg[i] = messageObjToString.charCodeAt(i);
+                       }
+                       try {
+                               if (socket !== null && socket.state === "OPEN") {
+                                       socket.writeData(sendTextMsg);
+                                       callback(message);
+                               }
+                       } catch (error) {
+                               console.error('sendMessage: ' + error.message);
+                       }
+               },
+
+               sendBye: function ClientModel_sendBye(name, socket) {
+                       var sendTextMsg = [], messageObj, messageObjToString, i, len;
+                       name = encodeURIComponent(name);
+                       messageObj = {name: name, text: '', ping: false, bye: true};
+                       messageObjToString = JSON.stringify(messageObj);
+                       len = messageObjToString.length;
+                       for (i = 0; i < len; i += 1) {
+                               sendTextMsg[i] = messageObjToString.charCodeAt(i);
+                       }
+                       try {
+                               if (socket !== null && socket.state === "OPEN") {
+                                       socket.writeData(sendTextMsg);
+                               }
+                       } catch (error) {
+                               console.error('sendBye: ' + error.message);
+                       }
+               },
+
+               destroyBonding: function ClientModel_destroyBonding(device, restartCallback, showStartButtonsCallback) {
+                       if (device !== null) {
+                               if (device.isBonded) {
+                                       this.client.adapter.destroyBonding(device.address, function () {
+                                               device = null;
+                                               restartCallback();
+                                       }, function (error) { console.error('ClientModel_destroyBonding: ' + error); });
+                               } else {
+                                       device = null;
+                                       restartCallback();
+                               }
+                       } else {
+                               this.stopServerSearching();
+                               showStartButtonsCallback();
+                       }
+               }
+
+       };
+}());
diff --git a/js/app.config.js b/js/app.config.js
new file mode 100644 (file)
index 0000000..c40c601
--- /dev/null
@@ -0,0 +1,29 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Config
+ */
+function Config() {
+       'use strict';
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       Config.prototype = {
+
+               properties: {
+                       'templateDir': 'templates',
+                       'templateExtension': '.tpl'
+               },
+
+               /**
+                * Returns config value
+                */
+               get: function (value, defaultValue) {
+                       if (this.properties.hasOwnProperty(value)) {
+                               return this.properties[value];
+                       }
+                       return defaultValue;
+               }
+       };
+}());
diff --git a/js/app.helpers.js b/js/app.helpers.js
new file mode 100644 (file)
index 0000000..0437bc6
--- /dev/null
@@ -0,0 +1,19 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Helpers
+ */
+function Helpers() {
+       'use strict';
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       Helpers.prototype = {
+
+               checkStringLength: function Helpers_checkStringLength(value) {
+                       return value.length > 0 ? true : false;
+               }
+
+       };
+}());
diff --git a/js/app.js b/js/app.js
new file mode 100644 (file)
index 0000000..114c13d
--- /dev/null
+++ b/js/app.js
@@ -0,0 +1,208 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+var App = null;
+
+(function () { // strict mode wrapper
+       'use strict';
+
+       /**
+        * Creates a new application object
+        *
+        * @class Application
+        */
+       App = function App() {};
+
+       App.prototype = {
+               /**
+                * @type Array
+                */
+               requires: ['js/app.config.js',
+                          'js/app.helpers.js',
+                          'js/app.model.js',
+                          'js/app.ui.js',
+                          'js/app.ui.templateManager.js',
+                          'js/app.ui.events.js',
+                          'js/app.client.js',
+                          'js/app.client.model.js',
+                          'js/app.server.js',
+                          'js/app.server.model.js'
+                          ],
+
+               /**
+                * @type Model
+                */
+               model: null,
+
+               /**
+                * @type Ui
+                */
+               ui: null,
+
+               /**
+                * @type Config
+                */
+               config: null,
+
+               /**
+                * @type Helpers
+                */
+               helpers: null,
+
+               /**
+                * @type Client
+                */
+               client: null,
+
+               /**
+                * @type Server
+                */
+               server: null,
+
+               /**
+                * @type String
+                */
+               currentName: '',
+
+               /**
+                * @type Boolean
+                */
+               doNotSendBye: false,
+
+               /**
+                * @type Boolean
+                */
+               connection: false,
+
+               /**
+                * Initialisation function
+                */
+               init: function App_init() {
+                       this.config = new Config();
+                       this.helpers = new Helpers();
+                       this.model = new Model();
+                       this.ui = new Ui(this.initModel.bind(this));
+               },
+
+               initModel: function App_initModel() {
+                       this.model.init(this.checkPowerState.bind(this));
+               },
+
+               /**
+                * exit application action
+                */
+               exit: function App_exit() {
+                       tizen.application.getCurrentApplication().exit();
+               },
+
+               isConnection: function App_isConnection() {
+                       return this.connection;
+               },
+
+               setConnection: function App_setConnection(boolean) {
+                       this.connection = boolean;
+               },
+
+               getDoNotSendBye: function App_getDoNotSendBye() {
+                       return this.doNotSendBye;
+               },
+
+               setDoNotSendBye: function App_setDoNotSendBye(boolean) {
+                       this.doNotSendBye = boolean;
+               },
+
+               getCurrentName: function App_getCurrentName() {
+                       return this.currentName;
+               },
+
+               getApplicationMode: function App_getApplicationMode() {
+                       var mode = 'start';
+                       if (this.client !== null) {
+                               mode = 'client';
+                       } else if (this.server !== null) {
+                               mode = 'server';
+                       }
+                       return mode;
+               },
+
+               resetApplicationMode: function App_resetApplicationMode() {
+                       this.client = null;
+                       this.server = null;
+               },
+
+               checkPowerState: function App_checkPowerState() {
+                       this.ui.setContentStartAttributes(
+                               this.model.checkPowerState.bind(
+                                       this.model, this.ui.showPowerOnButton, this.ui.showStartButtons
+                               )
+                       );
+               },
+
+               powerOn: function App_powerOn() {
+                       this.model.powerOn(this.ui.showStartButtons);
+               },
+
+               powerOff: function App_powerOff() {
+                       this.model.powerOff(this.exit);
+               },
+
+               restartBluetooth: function App_restartBluetooth() {
+                       this.model.restartBluetooth(this.powerOn.bind(this));
+               },
+
+               startServer: function App_startServer() {
+                       this.server = new Server(this.model.adapter, this.model.serviceUUID);
+                       this.showKeyboardPage();
+               },
+
+               startClient: function App_startClient() {
+                       this.client = new Client(this.model.adapter, this.model.serviceUUID);
+                       this.showKeyboardPage();
+               },
+
+               showKeyboardPage: function App_showKeyboardPage() {
+                       this.ui.showKeyboardPage();
+               },
+
+               setUserName: function App_setUserName(value) {
+                       this.currentName = value;
+               },
+
+               setAdapterName: function App_setAdapterName() {
+                       var changeName = false, mode = this.getApplicationMode();
+                       if (this.model.adapter.name !== this.currentName) {
+                               changeName = true;
+                       }
+                       if (mode === 'server') {
+                               this.model.setAdapterName(changeName, this.server.registerServer.bind(this.server));
+                       } else if (mode === 'client') {
+                               this.model.setAdapterName(changeName, this.client.searchServer.bind(this.client));
+                       }
+               },
+
+               clearListOfServers: function App_clearListOfServers() {
+                       this.ui.clearListOfServers();
+               },
+
+               displaySentMessage: function App_displaySentMessage(message) {
+                       this.ui.displaySentMessage(message);
+               },
+
+               sendMessage: function App_sendMessage(message) {
+                       var mode = this.getApplicationMode();
+                       if (mode === 'server') {
+                               this.server.sendMessage(message, this.displaySentMessage.bind(this));
+                       } else if (mode === 'client') {
+                               this.client.sendMessage(message, this.displaySentMessage.bind(this));
+                       }
+               },
+
+               sendBye: function App_sendBye() {
+                       var mode = this.getApplicationMode();
+                       if (mode === 'server') {
+                               this.server.sendBye();
+                       } else if (mode === 'client') {
+                               this.client.sendBye();
+                       }
+               }
+       };
+}());
diff --git a/js/app.model.js b/js/app.model.js
new file mode 100644 (file)
index 0000000..2882a7a
--- /dev/null
@@ -0,0 +1,75 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Model
+ */
+function Model() {
+       'use strict';
+       this.adapter = null;
+       this.serviceUUID = '5BCE9431-6C75-32AB-AFE0-2EC108A30860';
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       Model.prototype = {
+
+               /**
+                * API module initialisation
+                */
+               init: function Model_init(callback) {
+                       try {
+                               console.log('getDefaultAdapter');
+                               var time = new Date().getTime();
+                               this.adapter = tizen.bluetooth.getDefaultAdapter();
+                               console.log('getDefaultAdapter OK: ' + (new Date().getTime() - time) + ' milliseconds.');
+                               callback();
+                       } catch (error) {
+                               console.error('Problem with bluetooth device. Application can\'t work properly: ' + error.message);
+                       }
+               },
+
+               checkPowerState: function Model_checkPowerState(showPowerOnButtonCallback, showStartButtonsCallback) {
+                       if (!this.adapter.powered) {
+                               showPowerOnButtonCallback();
+                       } else {
+                               showStartButtonsCallback();
+                       }
+               },
+
+               powerOn: function Model_powerOn(callback) {
+                       if (!this.adapter.powered) {
+                               this.adapter.setPowered(true, function () { setTimeout(function () { callback(); }, 500); }, function () {});
+                       } else {
+                               callback();
+                       }
+               },
+
+               powerOff: function Model_powerOff(callback) {
+                       var app = tizen.application.getCurrentApplication();
+                       if (this.adapter.powered) {
+                               this.adapter.setPowered(false, function () { callback(); }, function () { callback(); });
+                       } else {
+                               callback();
+                       }
+               },
+
+               restartBluetooth: function Model_restartBluetooth(callback) {
+                       if (this.adapter.powered) {
+                               this.adapter.setPowered(false, function () { setTimeout(function () { callback(); }, 500); }, function () {});
+                       } else {
+                               callback();
+                       }
+               },
+
+               setAdapterName: function Model_setAdapterName(changeName, callback) {
+                       if (changeName) {
+                               this.adapter.setName(app.currentName, function () {
+                                       callback();
+                               }, function () {
+                               });
+                       } else {
+                               callback();
+                       }
+               }
+       };
+}());
diff --git a/js/app.server.js b/js/app.server.js
new file mode 100644 (file)
index 0000000..e3b2465
--- /dev/null
@@ -0,0 +1,94 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Server
+ */
+
+function Server(adapter, serviceUUID) {
+       'use strict';
+       this.adapter = adapter;
+       this.serviceUUID = serviceUUID;
+       this.numberOfClients = 0;
+       this.globalRecordHandler = null;
+       this.globalSocket = null;
+       this.init();
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+
+       Server.prototype = {
+               /**
+                * @type clientModel
+                */
+               model: null,
+
+               /**
+                * Initialisation function
+                */
+               init: function Server_init() {
+                       this.model = new ServerModel(this);
+                       return this;
+               },
+
+               getNumberOfClients: function Server_getNumberOfClients() {
+                       return this.numberOfClients;
+               },
+
+               registerServer: function Server_registerServer() {
+                       this.model.registerServer(this.adapter, this.serviceUUID, this.registerServerSuccess.bind(this));
+               },
+
+               registerServerSuccess: function Server_registerServerSuccess(recordHandler) {
+                       this.globalRecordHandler = recordHandler;
+                       recordHandler.onconnect = function (socket) {
+                               this.numberOfClients += 1;
+                               this.globalSocket = socket;
+                               socket.onmessage = function () {
+                                       var data, recvmsg = '', i, len, messageObj;
+                                       data = socket.readData();
+                                       len = data.length;
+                                       for (i = 0; i < len; i += 1) {
+                                               recvmsg += String.fromCharCode(data[i]);
+                                       }
+                                       messageObj = JSON.parse(recvmsg);
+                                       app.ui.displayReceivedMessage(messageObj.name, messageObj.text, messageObj.ping, messageObj.bye);
+                               };
+                               socket.onerror = function (e) {
+                                       console.error('Server onerror');
+                                       socket.close();
+                               };
+                               socket.onclose = function () {
+                                       this.globalSocket = null;
+                                       app.setConnection(false);
+                               };
+                               app.setConnection(true);
+                       }.bind(this);
+                       app.ui.showChatPage();
+               },
+
+               unregisterChatServer: function Server_unregisterChatServer() {
+                       this.model.unregisterChatServer(this.globalRecordHandler, this.unregisterChatServerSuccess.bind(this), this.unregisterChatServerError.bind(this), app.ui.showStartButtons);
+               },
+
+               unregisterChatServerSuccess: function Server_unregisterChatServerSuccess() {
+                       this.globalRecordHandler = null;
+                       this.numberOfClients = 0;
+                       app.restartBluetooth();
+               },
+
+               unregisterChatServerError: function Server_unregisterChatServerError() {
+                       console.error('Server_unregisterChatServerError');
+                       this.numberOfClients = 0;
+                       app.restartBluetooth();
+               },
+
+               sendMessage: function Server_sendMessage(message, callback) {
+                       this.model.sendMessage(this.adapter.name, this.globalSocket, message, callback);
+               },
+
+               sendBye: function Server_sendBye() {
+                       this.model.sendBye(this.adapter.name, this.globalSocket);
+               }
+       };
+}());
diff --git a/js/app.server.model.js b/js/app.server.model.js
new file mode 100644 (file)
index 0000000..10e9023
--- /dev/null
@@ -0,0 +1,82 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class Model
+ */
+function ServerModel(parent) {
+       'use strict';
+       this.server = parent;
+       this.init();
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       ServerModel.prototype = {
+
+               /**
+                * API module initialisation
+                */
+               init: function ServerModel_init() {},
+
+               registerServer: function ServerModel_registerServer(adapter, serviceUUID, callback) {
+                       if (this.server.getNumberOfClients() === 0) {
+                               try {
+                                       adapter.registerRFCOMMServiceByUUID(serviceUUID, 'Chat service', callback, function (error) { console.error(error.message); });
+                               } catch (error) {
+                                       console.error(error.message);
+                               }
+                       }
+               },
+
+               unregisterChatServer: function ServerModel_unregisterChatServer(globalRecordHandler, successCallback, errorCallback, showButtonsCallback) {
+                       try {
+                               if (globalRecordHandler !== null) {
+                                       globalRecordHandler.unregister(successCallback, errorCallback);
+                               } else {
+                                       showButtonsCallback();
+                               }
+                       } catch (error) {
+                               errorCallback();
+                       }
+               },
+
+               sendMessage: function ServerModel_sendMessage(name, socket, message, callback) {
+                       var sendTextMsg = [], messageObj, messageObjToString, i, len;
+                       name = encodeURIComponent(name);
+                       message = encodeURIComponent(message);
+                       messageObj = {name: name, text: message, ping: false, bye: false};
+                       messageObjToString = JSON.stringify(messageObj);
+                       len = messageObjToString.length;
+                       for (i = 0; i < len; i += 1) {
+                               sendTextMsg[i] = messageObjToString.charCodeAt(i);
+                       }
+                       try {
+                               if (socket !== null && socket.state === "OPEN") {
+                                       socket.writeData(sendTextMsg);
+                                       callback(message);
+                               }
+                       } catch (error) {
+                               console.error('sendMessage: ' + error.message);
+                       }
+               },
+
+               sendBye: function ServerModel_sendBye(name, socket) {
+                       var sendTextMsg = [], messageObj, messageObjToString, i, len;
+                       name = encodeURIComponent(name);
+                       messageObj = {name: name, text: '', ping: false, bye: true};
+                       messageObjToString = JSON.stringify(messageObj);
+                       len = messageObjToString.length;
+                       for (i = 0; i < len; i += 1) {
+                               sendTextMsg[i] = messageObjToString.charCodeAt(i);
+                       }
+                       try {
+                               if (socket !== null && socket.state === "OPEN") {
+                                       socket.writeData(sendTextMsg);
+                               }
+                       } catch (error) {
+                               console.error('sendBye: ' + error.message);
+                       }
+               }
+
+       };
+}());
diff --git a/js/app.ui.events.js b/js/app.ui.events.js
new file mode 100644 (file)
index 0000000..3fe782b
--- /dev/null
@@ -0,0 +1,178 @@
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+/**
+ * @class UiEvents
+ */
+function UiEvents(parent) {
+       'use strict';
+       this.ui = parent;
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       UiEvents.prototype = {
+
+               /**
+                * Initialization
+                */
+               init: function UiEvents_init() {
+                       this.addPageEvents();
+               },
+
+               /**
+                * Bind events to pages
+                */
+               addPageEvents: function UiEvents_addPageEvents() {
+                       var self = this;
+
+                       $('#start-header .ui-btn-back').on('tap', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               app.powerOff();
+                       });
+
+                       $('#choose-footer').on('tap', '.ui-btn-back', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               app.setDoNotSendBye(true);
+                               $.mobile.changePage('#start');
+                       });
+
+                       $('#chat-header').on('tap', '.ui-btn-back', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               if (!app.isConnection()) {
+                                       app.setDoNotSendBye(true);
+                               }
+                               $.mobile.changePage('#start');
+                       });
+
+                       $('#chat-header').on('tap', '.ui-btn-back', function (event) {
+                               event.preventDefault();
+                       });
+
+                       $('#start').on('pagebeforeshow', function () {
+                               self.ui.hideStartButtons();
+                               self.ui.clearChatDialog();
+                               if (!app.getDoNotSendBye()) {
+                                       app.sendBye();
+                               } else {
+                                       app.setDoNotSendBye(false);
+                               }
+                               if (app.getApplicationMode() === 'server') {
+                                       app.server.unregisterChatServer();
+                               } else if (app.getApplicationMode() === 'client') {
+                                       app.client.destroyBonding();
+                               }
+                       });
+
+                       $('#turnOnButton').on('tap', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               self.ui.hideStartButtons();
+                               app.powerOn();
+                       });
+
+                       $('#serverButton').on('tap', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               app.resetApplicationMode();
+                               app.startServer();
+                       });
+
+                       $('#clientButton').on('tap', function (event) {
+                               event.preventDefault();
+                               event.stopPropagation();
+                               app.resetApplicationMode();
+                               app.startClient();
+                       });
+
+                       $('#keyboard').on('pagebeforeshow', function () {
+                               $('#keyboard-text').val('').attr('placeholder', 'Type ' + app.getApplicationMode() + ' name');
+                               $('#keyboard-header > h1').html('Type ' + app.getApplicationMode() + ' name');
+                       });
+
+                       $('#keyboard').on('pageshow', function () {
+                               $('#keyboard-text').focus();
+                       });
+
+                       $('#keyboard-header').on('tap', '#keyboard-back-button', function (event) {
+                               event.preventDefault();
+                               app.setDoNotSendBye(true);
+                               $.mobile.changePage('#start');
+                       });
+
+                       $('#keyboard-header').on('tap', '#keyboard-ok-button', function (event) {
+                               event.preventDefault();
+                               var value = $('#keyboard-text').val(), mode;
+                               if (value.length !== 0) {
+                                       app.setUserName(value);
+                                       mode = app.getApplicationMode();
+                                       if (mode === 'server') {
+                                               app.setAdapterName();
+                                       } else if (mode === 'client') {
+                                               $.mobile.changePage('#choose');
+                                       }
+                               }
+                       });
+
+                       $('#choose').on('pagebeforeshow', function () {
+                               app.setAdapterName();
+                       });
+
+                       $('#choose').on('pagehide', function () {
+                               app.clearListOfServers();
+                               app.client.stopServerSearching();
+                       });
+
+                       $('#choose-content').on('tap', 'ul.ui-listview li', function () {
+                               app.client.stopServerSearching($(this).attr('address'));
+                       });
+
+                       $('#chat').on('pagebeforeshow', function () {
+                               $('#chat-header-type').html(app.getApplicationMode());
+                               $('#chat-header-name').html(app.getCurrentName());
+                               if ($(this).data('serverName') !== undefined) {
+                                       $('#chat-header-type').append(' - connected to ' + $(this).data('serverName'));
+                                       $(this).removeData('serverName');
+                               }
+                               self.ui.checkSendButtonState();
+                       });
+
+                       $('#chat').on('pageshow', function () {
+                               if (app.getApplicationMode() === 'server') {
+                                       setTimeout(function() { app.ui.showVisibilityPopup(); }, 100);
+                               }
+                       });
+
+                       $('#text').on('input', function () {
+                               self.ui.checkSendButtonState();
+                       });
+
+                       $('#ui-mySend').on('tap', function (event) {
+                               event.stopPropagation();
+                               var message = $('#text').val();
+                               $('#text').val('');
+                               self.ui.disableSendButton();
+                               app.sendMessage(message);
+                       });
+
+                       $('body').on('tap', '#byeOK' , function () {
+                               self.ui.hideByePopup();
+                               $('#keyboard-back-button').trigger('tap');
+                       });
+
+                       $('body').on('touchstart', '#byePopup-screen' , function () {
+                               $('#byeOK').trigger('tap');
+                       });
+
+                       $('body').on('tap', '#visibilityOK' , function () {
+                               self.ui.hideVisibilityPopup();
+                       });
+
+                       $('body').on('touchstart', '#visibilityPopup-screen' , function () {
+                               $('#visibilityOK').trigger('tap');
+                       });
+               }
+       };
+}());
diff --git a/js/app.ui.js b/js/app.ui.js
new file mode 100644 (file)
index 0000000..6fe669f
--- /dev/null
@@ -0,0 +1,226 @@
+/*jslint devel: true */
+/*global $, tizen, app, UiEvents, TemplateManager, document, window, setTimeout */
+/**
+ * @class Ui
+ */
+
+function Ui(callback) {
+       'use strict';
+       this.init(callback);
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       Ui.prototype = {
+
+               templateManager: null,
+
+               /**
+                * UI object for UI events
+                */
+               uiEvents: null,
+
+               /**
+                * UI module initialisation
+                */
+               init: function Ui_init(callback) {
+                       this.templateManager = new TemplateManager();
+                       this.uiEvents = new UiEvents(this);
+                       $.mobile.tizen.disableSelection(document);
+
+                       $(document).ready(this.domInit.bind(this, callback));
+               },
+
+               /**
+                * When DOM is ready, initialise it (bind events)
+                */
+               domInit: function Ui_domInit(callback) {
+                       var templates = ['keyboard_page',
+                                        'chat_page',
+                                        'choose_page',
+                                        'server_row',
+                                        'left_bubble',
+                                        'right_bubble',
+                                        'bye_popup',
+                                        'visibility_popup'
+                       ];
+
+                       this.templateManager.loadToCache(templates, this.initPages.bind(this, callback));
+               },
+
+               initPages: function Ui_initPages(callback) {
+                       var pages = [], body = $('body');
+
+                       body.append(this.templateManager.get('bye_popup')).append(this.templateManager.get('visibility_popup')).trigger('create');
+
+                       pages.push(this.templateManager.get('keyboard_page'));
+                       pages.push(this.templateManager.get('chat_page'));
+                       pages.push(this.templateManager.get('choose_page'));
+                       body.append(pages.join(''));
+
+                       this.uiEvents.init();
+
+                       callback();
+               },
+
+               setContentStartAttributes: function Ui_setContentStartAttributes(callback) {
+                       var contentStart, contentStartHeight;
+                       contentStart = $('#start-content');
+                       if (contentStart.height() > $(window).height()) {
+                               contentStartHeight = $(window).height() - $('#start-header').height()
+                                       - parseInt(contentStart.css('padding-top'), 10) - parseInt(contentStart.css('padding-bottom'), 10);
+                       } else {
+                               contentStartHeight = contentStart.height();
+                       }
+                       setTimeout(function () { // workaround (setTimeout with 0 delay)
+                               contentStart
+                                       .css('height', contentStartHeight  + 'px')
+                                       .css('min-height', 'auto')
+                                       .css('width', contentStart.width() + 'px');
+                               $('#start').css('min-height', 'auto');
+                               callback();
+                       }, 0);
+               },
+
+               showChatPage: function Ui_showChatPage(serverName) {
+                       if (serverName !== undefined) {
+                               $('#chat').data('serverName', serverName);
+                       }
+                       $.mobile.changePage('#chat');
+               },
+
+               showKeyboardPage: function Ui_showKeyboardPage() {
+                       $.mobile.changePage('#keyboard');
+               },
+
+               clearChatDialog: function Ui_clearChatDialog() {
+                       $('#chat-content .ui-listview').empty();
+               },
+
+               showPowerOnButton: function Ui_showPowerOnButton() {
+                       $('#start-monit').hide();
+                       $('#serverButton').hide();
+                       $('#clientButton').hide();
+                       $('#turnOnButton').show();
+               },
+
+               showStartButtons: function Ui_showStartButtons() {
+                       $('#start-monit').hide();
+                       $('#turnOnButton').hide();
+                       $('#serverButton').show();
+                       $('#clientButton').show();
+               },
+
+               hideStartButtons: function Ui_hideStartButtons() {
+                       $('#serverButton').hide();
+                       $('#clientButton').hide();
+                       $('#turnOnButton').hide();
+                       $('#start-monit').show();
+               },
+
+               addDeviceToList: function Ui_addDeviceToList(device) {
+                       var listElement, address, sub2, ul = $('#choose-content ul.ui-listview');
+
+                       listElement = this.templateManager.get('server_row', {
+                               'deviceAddress': device.address,
+                               'deviceName': device.name
+                       });
+
+                       ul.append(listElement);
+                       ul.listview('refresh');
+               },
+
+               clearListOfServers: function Ui_clearListOfServers() {
+                       $('#choose-content ul.ui-listview').empty();
+               },
+
+               showByePopup: function Ui_showByePopup(name) {
+                       var mode = app.getApplicationMode(), message = $('#byeMessage');
+                       if (mode === 'server') {
+                               message.html('Client name "' + name + '" is unavailable.\nYour bluetooth device will be automatically restarted.');
+                       } else if (mode === 'client') {
+                               message.html('Server name "' + name + '" is unavailable.\nYour bluetooth device will be automatically restarted.');
+                       }
+                       $('#byePopup').popup('open', {'positionTo': 'window'});
+               },
+
+               hideByePopup: function Ui_hideByePopup() {
+                       $('#byePopup').popup('close');
+               },
+
+               showVisibilityPopup: function Ui_showVisibilityPopup() {
+                       $('#visibilityPopup').popup('open', {'positionTo': 'window'});
+               },
+
+               hideVisibilityPopup: function Ui_hideVisibilityPopup() {
+                       $('#visibilityPopup').popup('close');
+               },
+
+               displayReceivedMessage: function Ui_displayReceivedMessage(name, text, ping, bye) {
+                       var listElement, span, ul;
+                       text = decodeURIComponent(text);
+                       name = decodeURIComponent(name);
+                       if (bye) {
+                               this.showByePopup(name);
+                       } else if (ping) {
+                               app.setConnection(true);
+                               $('#chat-header-type').append(' - connected with ' + name);
+                               this.checkSendButtonState();
+                       } else {
+                               listElement = this.templateManager.get('left_bubble', {
+                                       'text': text
+                               });
+                               ul = $('#chat-content > .ui-scrollview-view > ul');
+                               ul.append(listElement);
+                               ul.listview('refresh');
+                       }
+               },
+
+               enableSendButton: function Ui_enableSendButton() {
+                       $('#ui-mySend')
+                               .css({'pointer-events': 'auto', 'color': '#000'})
+                               .removeClass('ui-disabled');
+               },
+
+               disableSendButton: function Ui_disableSendButton() {
+                       $('#ui-mySend')
+                               .css({'pointer-events': 'none', 'color': '#bbb'})
+                               .removeClass('ui-btn-down-s')
+                               .addClass('ui-disabled');
+               },
+
+               checkSendButtonState: function Ui_checkSendButtonState() {
+                       if (app.helpers.checkStringLength($('#text').val().trim()) && app.isConnection()) {
+                               this.enableSendButton();
+                       } else {
+                               this.disableSendButton();
+                       }
+               },
+
+               moveMessagesListDown: function Ui_moveMessagesListDown(content, listHeight) {
+                       var delta = content.height() - listHeight;
+                       if (delta < 0) {
+                               content.scrollview('scrollTo', 0, delta, 500);
+                       }
+               },
+
+               displaySentMessage: function Ui_displaySentMessage(message) {
+                       var listElement, span, ul, content, self = this;
+                       message = decodeURIComponent(message);
+                       listElement = this.templateManager.get('right_bubble', {
+                               'text': message
+                       });
+                       content = $('#chat-content');
+                       ul = content.find('ul');
+                       ul.append(listElement);
+                       ul.listview('refresh');
+                       setTimeout(function () { self.moveMessagesListDown(content, ul.height()) }, 200);
+               },
+
+               setDiscoveringProgress: function Ui_setDiscoveringProgress(boolean) {
+                       $('#discovering').progress('hide', !boolean).progress('running', boolean);
+               }
+
+       };
+
+}());
diff --git a/js/app.ui.templateManager.js b/js/app.ui.templateManager.js
new file mode 100644 (file)
index 0000000..68c6678
--- /dev/null
@@ -0,0 +1,111 @@
+/*global tizen, $, app */
+/**
+ * @class TemplateManager
+ */
+function TemplateManager() {
+       'use strict';
+       this.init();
+}
+
+(function () { // strict mode wrapper
+       'use strict';
+       TemplateManager.prototype = {
+
+               /**
+                * Template cache
+                */
+               cache: {},
+
+               /**
+                * UI module initialisation
+                */
+               init: function init() {
+               },
+
+               /**
+                * Returns template html (from cache)
+                * @param {string} tplName
+                * @param {string} tplParams
+                */
+               get: function TemplateManager_get(tplName, tplParams) {
+                       if (this.cache[tplName] !== undefined) {
+                               return this.getCompleted(this.cache[tplName], tplParams);
+                       }
+                       return '';
+               },
+
+               /**
+                * Load templates to cache
+                * @param {string} tplNames
+                * @param {function} onSuccess
+                */
+               loadToCache: function TemplateManager_loadToCache(tplNames, onSuccess) {
+                       var self = this,
+                               cachedTemplates = 0,
+                               tplName,
+                               tplPath;
+
+                       if ($.isArray(tplNames)) {
+
+                               // for each template
+                               $.each(tplNames, function (index, fileName) {
+
+                                       // cache template html
+                                       if (self.cache[fileName] === undefined) {
+                                               tplName = [fileName, app.config.get('templateExtension')].join('');
+                                               tplPath = [app.config.get('templateDir'), tplName].join('/');
+
+                                               $.ajax({
+                                                       url: tplPath,
+                                                       cache: true,
+                                                       dataType: 'html',
+                                                       async: true,
+                                                       success: function (data) {
+                                                               // increase counter
+                                                               cachedTemplates += 1;
+
+                                                               // save to cache
+                                                               self.cache[fileName] = data;
+
+                                                               // if all templates are cached launch callback
+                                                               if (cachedTemplates >= tplNames.length && typeof onSuccess === 'function') {
+                                                                       onSuccess();
+                                                               }
+                                                       },
+                                                       error: function (jqXHR, textStatus, errorThrown) {
+                                                               console.error('templateManagerError: ' + errorThrown);
+                                                       }
+                                               });
+                                       } else {
+                                               // template is already cached
+                                               cachedTemplates += 1;
+                                               // if all templates are cached launch callback
+                                               if (cachedTemplates >= tplNames.length && typeof onSuccess === 'function') {
+                                                       onSuccess();
+                                               }
+                                       }
+                               });
+
+                       }
+               },
+
+               /**
+                * Returns template completed by specified params
+               * @param {string} tplHtml
+               * @param {string} tplParams
+                */
+               getCompleted: function TemplateManager_getCompleted(tplHtml, tplParams) {
+                       var tplParam, replaceRegExp;
+
+                       for (tplParam in tplParams) {
+                               if (tplParams.hasOwnProperty(tplParam)) {
+                                       replaceRegExp = new RegExp(['%', tplParam, '%'].join(''), 'g');
+                                       tplHtml = tplHtml.replace(replaceRegExp, tplParams[tplParam]);
+                               }
+                       }
+
+                       return tplHtml;
+               }
+       };
+
+}());
\ No newline at end of file
index cd92c1f..cdf1ce3 100644 (file)
@@ -1,3 +1,4 @@
+/*jslint devel: true*/
 /*global $, tizen, app */
 
 var client = {
@@ -5,7 +6,7 @@ var client = {
                "use strict";
                var sendTextMsg, messageObj, messageObjToString, i, len;
                sendTextMsg = [];
-               messageObj = {name: app.currentName, text: '', ping: true, bye: false};
+               messageObj = {name: encodeURIComponent(app.currentName), text: '', ping: true, bye: false};
                messageObjToString = JSON.stringify(messageObj);
                len = messageObjToString.length;
 
@@ -17,7 +18,7 @@ var client = {
                                app.globalSocket.writeData(sendTextMsg);
                        }
                } catch (error) {
-                       console.log('sendPing: ' + error.message);
+                       console.error('sendPing: ' + error.message);
                }
        },
 
@@ -43,10 +44,13 @@ var client = {
                        socket.close();
                };
                socket.onclose = function () {
+                       app.connection = false;
+                       app.checkChatSendButtonState();
                        app.globalSocket = null;
                };
                $('#chat-title').text('Client: ' + app.currentName + ' << >> ' + app.chatServerDevice.name);
                app.connection = true;
+               app.checkChatSendButtonState();
                client.sendPing();
        },
 
@@ -58,32 +62,30 @@ var client = {
 
        bondSuccess: function bondSuccess(device) {
                "use strict";
-               //$('.ui-loader').hide();
 
                app.chatServerDevice = device;
 
                try {
                        device.connectToServiceByUUID(app.serviceUUID, client.onSocketConnected, client.onSocketError, 'RFCOMM');
                } catch (exc) {
-                       console.log('connectToServiceByUUID: ' + exc.message + '<br/>');
+                       console.error('connectToServiceByUUID: ' + exc.message + '<br/>');
                }
        },
 
        bondError: function bondError(error) {
                "use strict";
-               //$('.ui-loader').hide();
+
                $('#choose-content').find('ul li').css('background-color', '#fff');
                app.showPopup('Bonding problem with selected device. Try again. ' + error.message, $('#choose'));
        },
 
        addDeviceToList: function addDeviceToList(ul, chooseContent, device) {
                "use strict";
-               var listElement, name, address, sub2,
+               var listElement, address, sub2,
                        startBonding = function (element, address) {
-                               app.adapter.createBonding(address, client.bondSuccess, client.bondSuccess);
+                               app.adapter.createBonding(address, client.bondSuccess, client.bondError);
                                ul.find('li').css('background-color', '#fff');
                                element.css('background-color', '#aaa');
-                               //app.showLoader('Waiting for response...');
                        };
                if ($.inArray(device.address, app.deviceAddresses) === -1) {
                        app.deviceAddresses.push(device.address);
@@ -98,13 +100,13 @@ var client = {
                                address = $(this).attr('address');
                                element = $(this);
                                if (app.discovering) {
-                                       console.log('discovering');
                                        app.adapter.stopDiscovery(function () {
                                                app.discovering = false;
                                                startBonding(element, address);
-                                       }, function (e) { console.log('stopDiscovery error: ' + e.message); });
+                                       }, function (e) {
+                                               console.error('stopDiscovery error: ' + e.message);
+                                       });
                                } else {
-                                       console.log('!discovering');
                                        startBonding(element, address);
                                }
                        });
@@ -127,9 +129,7 @@ var client = {
                        ondevicefound: function (device) {
                                client.addDeviceToList(ul, chooseContent, device);
                        },
-                       ondevicedisappeared: function (address) {
-                               console.log('device disappeared');
-                       },
+                       ondevicedisappeared: function (address) {},
                        onfinished: function (devices) { app.discovering = false; }
                };
 
index d5e6e3e..48be204 100644 (file)
  *      limitations under the License.
  */
 
-/*jslint devel: true*/
-/*global $: false, tizen: false */
-/*global server, client */
-var app = {
-       adapter: null,
-       serviceUUID: '5bce9431-6c75-32ab-afe0-2ec108a30860',
-       mode: null,
-       currentName: null,
-       maxMessageLength: 160,
-       doNotSendBye: false,
-       currentPage: 'start',
-       connection: false,
-       chatServiceHandler: null,
-       globalSocket: null,
-       chatServerDevice: null,
-       messageWindow: null,
-       deviceAddresses: [],
-       discovering: false,
-       numberOfClients: 0,
-
-       showLoader: function showLoader(message) {
-               "use strict";
-               var loader = $('.ui-loader');
-               loader.css('background', '-webkit-linear-gradient(top, #5A99BA 0%, #205473 100%)');
-               loader.css('color', 'white');
-               loader.find('h1').text(message);
-               loader.show();
-       },
-
-       showPopup: function showPopup(message, page) {
-               "use strict";
-               app.messageWindow = $('<div id="popup" data-role="popupwindow" data-style="center_basic_1btn"><p data-role="text">' + message + '</p><div data-role="button-bg"><a href="#" data-role="button" data-inline="true" onclick="app.closePopup();">OK</a></div></div>');
-               page.append(app.messageWindow);
-               page.trigger('create');
-               app.messageWindow.popupwindow('open');
-       },
-
-       closePopup: function closePopup() {
-               "use strict";
-               this.messageWindow.popupwindow('close');
-               this.messageWindow.remove();
-       },
-
-       showRestartPopup: function showRestartPopup(message, page) {
-               "use strict";
-               this.messageWindow = $('<div id="popup" data-role="popupwindow" data-style="center_basic_1btn"><p data-role="text">' + message + '</p><div data-role="button-bg"><a href="#" data-role="button" data-inline="true" onclick="app.closeRestartPopup();">OK</a></div></div>');
-               page.append(this.messageWindow);
-               page.trigger('create');
-               this.messageWindow.popupwindow('open');
-       },
-
-       closeRestartPopup: function closeRestartPopup() {
-               "use strict";
-               this.doNotSendBye = true;
-               this.messageWindow.popupwindow('close');
-               this.messageWindow.remove();
-               this.goToStartPage();
-       },
-
-       showTextInput: function showTextInput() {
-               "use strict";
-               console.log('showTextInput');
-               $.mobile.changePage('#keyboard');
-       },
-
-       chooseServer: function chooseServer() {
-               "use strict";
-               console.log('chooseServer');
-               app.mode = 'server';
-               app.showTextInput();
-       },
-
-       chooseClient: function chooseClient() {
-               "use strict";
-               console.log('chooseClient');
-               app.mode = 'client';
-               app.showTextInput();
-       },
-
-       scrollChatContentDown: function scrollChatContentDown() {
-               "use strict";
-               var newHeight, chatListHeight, scrollTo;
-               if (this.currentPage === 'chat') {
-                       newHeight = $('#chat').outerHeight() - $('#chat-header').outerHeight() - $('#chat-footer').outerHeight();
-                       $('#chat-content').css('height', newHeight + 'px');
-                       chatListHeight = $('#chat-content .ui-scrollview-view ul').outerHeight();
-                       scrollTo = newHeight - chatListHeight;
-                       if (scrollTo < 0) {
-                               $('#chat-content > .ui-scrollview-view').css('-webkit-transform', 'translate3d(0px, ' + scrollTo + 'px, 0px)');
-                               setTimeout(function () {$('#chat-content').scrollview('scrollTo', 0, (scrollTo)); }, 100);
-                       } else {
-                               $('#chat-content > .ui-scrollview-view').css('-webkit-transform', 'translate3d(0px, 0px, 0px)');
-                               $('#chat-content').scrollview('scrollTo', 0, 0);
-                       }
-               }
-       },
-
-       setTextareaHeight: function setTextareaHeight() {
-               "use strict";
-               console.log('setTextareaHeight');
-               var keyboardHeight, keyboardHeaderHeight, keyboardFooterHeight;
-               keyboardHeight = $('#keyboard').innerHeight();
-               keyboardHeaderHeight = $('#keyboard-header').innerHeight();
-               keyboardFooterHeight = $('#keyboard-footer').innerHeight();
-
-               if ($('#keyboard-footer').css('display') === 'none') {
-                       $('#keyboard-content').css('height', (keyboardHeight - keyboardHeaderHeight) + 'px');
-                       $('#keyboard-text').css('height', (keyboardHeight - keyboardHeaderHeight - 5) + 'px');
-               } else {
-                       $('#keyboard-content').css('height', (keyboardHeight - keyboardHeaderHeight - keyboardFooterHeight) + 'px');
-                       $('#keyboard-text').css('height', (keyboardHeight - keyboardHeaderHeight - keyboardFooterHeight - 5) + 'px');
-               }
-
-               $('#keyboard-content > .ui-scrollview-view').css('-webkit-transform', 'translate3d(0px, 0px, 0px)');
-               $('#keyboard-content').scrollview('scrollTo', 0, 0);
-       },
-
-       showStartButtons: function showStartButtons() {
-               "use strict";
-               $('#start-monit').hide();
-               $('#serverButton').show();
-               $('#clientButton').show();
-       },
-
-       hideStartButtons: function hideStartButtons() {
-               "use strict";
-               $('#serverButton').hide();
-               $('#clientButton').hide();
-               $('#start-monit').show();
-       },
-
-       goToStartPage: function goToStartPage() {
-               "use strict";
-               $.mobile.changePage('#start');
-       },
-
-       hideTextInput: function hideTextInput() {
-               "use strict";
-               console.log('hideTextInput');
-               this.currentName = $('#keyboard-text').val().substring(0, 5);
-               $('#keyboard-text').val('');
-               if (this.mode === 'server') {
-                       $.mobile.changePage('#chat');
-               } else {
-                       $.mobile.changePage('#choose');
-               }
-       },
-
-       changeName: function changeName(callback) {
-               "use strict";
-               if (this.adapter.name !== this.currentName) {
-                       this.adapter.setName(this.currentName, function () {
-                               callback();
-                       }, function () {
-                               console.log('Problem with bluetooth name.<br>Application can\'t set device name.');
-                       });
-               } else {
-                       callback();
-               }
-       },
-
-       displayReceivedMessage: function displayReceivedMessage(name, text, ping, bye) {
-               "use strict";
-               var listElement, span, ul;
-               if (bye) {
-                       if (app.mode === 'server') {
-                               app.showRestartPopup('Client name "' + name + '" is unavailable.\nYour bluetooth device will be automatically restarted.', $('#chat'));
-                       } else {
-                               app.showRestartPopup('Server name "' + name + '" is unavailable.\nYour bluetooth device will be automatically restarted.', $('#chat'));
-                       }
-               } else if (!ping) {
-                       listElement = $('<li class="ui-li-bubble-left"></li>');
-                       listElement.text(text);
-                       span = $('<br/><span class="ui-li-bubble-time"></span>');
-                       span.text(name);
-                       listElement.append(span);
-                       ul = $('#chat-content > .ui-scrollview-view > ul');
-                       ul.append(listElement);
-                       ul.listview('refresh');
-               } else {
-                       $('#chat-title').text('Server: ' + app.currentName + ' << >> ' + name);
-                       app.connection = true;
-               }
-       },
-
-       displaySentMessage: function displaySentMessage(message) {
-               "use strict";
-               var listElement, span, ul;
-               listElement = $('<li class="ui-li-bubble-right"></li>');
-               listElement.text(message);
-               span = $('<br/><span class="ui-li-bubble-time"></span>');
-               span.text(app.currentName);
-               listElement.append(span);
-               ul = $('#chat-content > .ui-scrollview-view > ul');
-               ul.append(listElement);
-               ul.listview('refresh');
-       },
-
-       sendMessage: function sendMessage() {
-               "use strict";
-               var value, sendTextMsg = [], messageObj, messageObjToString, i, len;
-               value = $('#text').val();
-               messageObj = {name: this.currentName, text: value, ping: false, bye: false};
-               messageObjToString = JSON.stringify(messageObj);
-               len = messageObjToString.length;
-               for (i = 0; i < len; i += 1) {
-                       sendTextMsg[i] = messageObjToString.charCodeAt(i);
-               }
-               try {
-                       if (this.globalSocket !== null && this.globalSocket.state === "OPEN") {
-                               this.globalSocket.writeData(sendTextMsg);
-                               this.displaySentMessage(value);
-                               setTimeout(function () { $('#text').val(''); }, 1000);
-                       }
-               } catch (error) {
-                       console.log('sendMessage: ' + error.message);
-               }
-       },
-
-       restartBluetooth: function restartBluetooth() {
-               "use strict";
-               var powerOff = function () {
-                       app.connection = false;
-                       if (app.adapter.powered) {
-                               var powerOn = function () {
-                                       if (!app.adapter.powered) {
-                                               app.adapter.setPowered(true, function () { setTimeout(function () { app.showStartButtons(); }, 1000); }, function () { setTimeout(function () { $('#start-monit p').html('... problem with bluetooth radio ...'); }, 1000); });
-                                       } else {
-                                               app.showStartButtons();
-                                       }
-                               };
-                               app.adapter.setPowered(false, function () { setTimeout(function () { powerOn(); }, 1000); }, function () { $('#start-monit p').html('... problem with bluetooth radio ...'); });
-                       }
-               };
-               if (app.adapter.visible) {
-                       app.adapter.setVisible(false, powerOff, function () { $('#start-monit p').html('... problem with bluetooth radio ...'); });
-               } else {
-                       powerOff();
-               }
-       },
-
-       sendBye: function sendBye() {
-               "use strict";
-               var sendTextMsg = [], messageObj, messageObjToString, i, len;
-               messageObj = {name: this.currentName, text: '', ping: false, bye: true};
-               messageObjToString = JSON.stringify(messageObj);
-               len = messageObjToString.length;
-               for (i = 0; i < len; i += 1) {
-                       sendTextMsg[i] = messageObjToString.charCodeAt(i);
-               }
-               try {
-                       if (this.globalSocket !== null && this.globalSocket.state === "OPEN") {
-                               this.globalSocket.writeData(sendTextMsg);
-                       }
-               } catch (error) {
-                       console.log('sendBye: ' + error.message);
-               }
-       },
-
-       addEvents: function addEvents() {
-               "use strict";
-               $(window).on('resize', function () {
-                       app.setTextareaHeight();
-                       app.scrollChatContentDown();
-               });
-
-               $('#start-footer-back').on('tap', function (event) {
-                       event.preventDefault();
-                       app.powerOff();
-               });
-
-               $('#keyboard-back-button').on('tap', function (event) {
-                       event.preventDefault();
-                       app.doNotSendBye = true;
-                       app.goToStartPage();
-               });
-
-               $('#keyboard-ok-button').on('tap', function (event) {
-                       event.preventDefault();
-                       if ($('#keyboard-text').val().length !== 0) {
-                               app.hideTextInput();
-                       }
-               });
-
-               $('#serverButton').on('tap', app.chooseServer);
-
-               $('#clientButton').on('tap', app.chooseClient);
-
-               $('#keyboard').on('pagebeforeshow', function () {
-                       app.currentPage = 'keyboard';
-                       $('#keyboard-text').val('');
-                       $('#keyboard-header > h1').html('Type ' + app.mode + ' name');
-               });
-
-               $('#keyboard').on('pageshow', function () {
-                       app.setTextareaHeight();
-                       $('#keyboard-text').focus();
-               });
-
-               $('#keyboard-text').on('keydown', function (event) {
-                       if (event.keyCode === 13 && $(this).val().split("\n").length >= 1) {
-                               return false;
-                       }
-               });
-
-               $('#start').on('pagebeforeshow', function () {
-                       app.currentPage = 'start';
-                       $('#start-monit p').html('... waiting for bluetooth radio ...');
-                       if (!app.doNotSendBye) {
-                               app.sendBye();
-                       } else {
-                               app.doNotSendBye = false;
-                       }
-                       app.hideStartButtons();
-                       $('#chat-title').html('');
-                       if (app.mode === 'server') {
-                               server.unRegisterChatService();
-                       } else {
-                               $('#choose-content .ui-scrollview-view').empty();
-                               if (app.chatServerDevice !== null) {
-                                       if (app.chatServerDevice.isBonded) {
-                                               app.adapter.destroyBonding(app.chatServerDevice.address, function () {
-                                                       app.chatServerDevice = null;
-                                                       app.chatServiceHandler = null;
-                                                       app.restartBluetooth();
-                                               }, function () {});
-                                       } else {
-                                               app.chatServiceHandler = null;
-                                               app.restartBluetooth();
-                                       }
-                               } else {
-                                       app.adapter.stopDiscovery(function () {}, function () {});
-                                       app.showStartButtons();
-                               }
-                       }
-               });
-
-               $('#choose').on('pagebeforeshow', function () {
-                       app.currentPage = 'choose';
-                       app.changeName(client.searchServer);
-               });
-
-               $('#chat').on('pagebeforeshow', function () {
-                       app.currentPage = 'chat';
-                       $('#chat-content > .ui-scrollview-view').empty();
-                       $('#text').val('');
-                       if (app.mode === 'server') {
-                               app.changeName(server.setServerVisible);
-                       }
-               });
-
-               $('#chat').on('pageshow', function () {
-                       var chatContent, ul;
-                       chatContent = $('#chat-content');
-                       ul = $('<ul data-role="listview"></ul>');
-                       chatContent.find('.ui-scrollview-view').append(ul);
-                       chatContent.trigger('create');
-               });
-
-               $('#text').on('tap', function (event) {
-                       event.stopPropagation();
-               });
-
-               /*
-               $('#text').on('focus', function () {
-                       $(this).addClass('focus');
-               });
-
-               $('#text').on('blur', function () {
-                       $(this).removeClass('focus');
-                       $('#chat-footer').css('display', 'block');
-               });
-               */
-
-               $('#choose-footer').on('tap', 'a.ui-btn-back', function (event) {
-                       event.preventDefault();
-                       app.doNotSendBye = true;
-                       app.goToStartPage();
-               });
-
-               $('#keyboard-footer').on('tap', 'a.ui-btn-back', function (event) {
-                       event.preventDefault();
-                       app.doNotSendBye = true;
-                       app.goToStartPage();
-               });
-
-               $('#ui-mySend').on('tap', function (event) {
-                       event.stopPropagation();
-                       if (app.connection) {
-                               if ($('#text').val().length > 0) {
-                                       app.sendMessage();
-                               } else {
-                                       app.showPopup('There is nothing to send.', $('#chat'));
-                               }
-                       } else {
-                               app.showPopup('There is no connection to other device. Wait for connection.', $('#chat'));
-                       }
-               });
-
-               $('#choose-header').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#choose-content').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#choose-footer').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#chat-header').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#chat-content').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#chat-footer').on('tap', function (event) {
-                       event.preventDefault();
-               });
-
-               $('#chat-header').on('tap', '#chat-back-button', function (event) {
-                       event.preventDefault();
-                       if (!app.connection) {
-                               app.doNotSendBye = true;
+/*jslint plusplus: true, sloppy: true, todo: true, vars: true, browser: true, devel: true, maxerr: 999 */
+/*global $, tizen, app */
+var app = null;
+
+(function () { // strict mode wrapper
+       'use strict';
+
+       ({
+               /**
+                * Loader init - load the App constructor
+                */
+               init: function init() {
+                       var self = this;
+                       $.getScript('js/app.js')
+                               .done(function () {
+                                       app = new App();
+                                       self.loadLibs();
+                               })
+                               .fail(this.onGetScriptError);
+               },
+
+               /**
+                * Load dependencies
+                */
+               loadLibs: function loadLibs() {
+                       var loadedLibs = 0;
+                       if ($.isArray(app.requires)) {
+                               $.each(app.requires, function (index, filename) {
+                                       $.getScript(filename)
+                                               .done(function () {
+                                                       loadedLibs += 1;
+                                                       if (loadedLibs >= app.requires.length) {
+                                                               app.init();
+                                                       }
+                                               })
+                                               .fail(this.onGetScriptError);
+                               });
                        }
-                       app.goToStartPage();
-               });
-
-               $('#keyboard-header').on('click', function (event) {
-                       event.preventDefault();
-                       $('#keyboard-text').focus();
-               });
+               },
 
-               $('#keyboard-header').on('tap', function (event) {
-                       event.preventDefault();
-                       $('#keyboard-text').focus();
-               });
-
-               //FIXME - temporary workaround which allows application testing (messages sending)
-               $('#text').on('focus', function () {
-                       console.log('FOCUS on: #text');
-                       setTimeout(function () { $('#chat-footer').show(); }, 1000);
-               });
-
-       },
-
-       powerOn: function powerOn() {
-               "use strict";
-               if (!this.adapter.powered) {
-                       this.adapter.setPowered(true, function () { setTimeout(function () { app.showStartButtons(); }, 1000); }, function () { setTimeout(function () { $('#start-monit p').html('... problem with bluetooth radio ...'); }, 1000); });
-               } else {
-                       app.showStartButtons();
-               }
-       },
-
-       powerOff: function powerOff() {
-               "use strict";
-               var app = tizen.application.getCurrentApplication();
-               if (this.adapter.powered) {
-                       this.adapter.setPowered(false, function () { app.exit(); }, function () { app.exit(); });
-               } else {
-                       app.exit();
+               /**
+                * Handle ajax errors
+                */
+               onGetScriptError: function onGetScriptError(e, jqxhr, setting, exception) {
+                       console.error('An error occurred: ' + e.message);
                }
-       },
-
-       getBluetoothAdapter: function getBluetoothAdapter() {
-               "use strict";
-               try {
-                       this.adapter = tizen.bluetooth.getDefaultAdapter();
-                       this.powerOn();
-               } catch (error) {
-                       console.log('Problem with bluetooth device. Application can\'t work properly.');
-               }
-       },
-
-       initFooter: function initFooter() {
-               "use strict";
-               $('#start-footer .ui-btn-back').attr('id', 'start-footer-back');
-       },
-
-       init: function init() {
-               "use strict";
-               app.initFooter();
-               app.addEvents();
-               app.getBluetoothAdapter();
-       }
-};
-
-$(document).ready(app.init);
+       }).init(); // run the loader
+}());
index 1e2146e..10d779c 100644 (file)
@@ -14,7 +14,6 @@ var server = {
                $('#chat-title').text('Server: ' + app.currentName);
                app.chatServiceHandler = recordHandler;
                recordHandler.onconnect = function (socket) {
-                       var peerName;
                        app.numberOfClients += 1;
                        server.hideMe();
                        app.globalSocket = socket;
@@ -29,21 +28,17 @@ var server = {
                                app.displayReceivedMessage(messageObj.name, messageObj.text, messageObj.ping, messageObj.bye);
                        };
                        socket.onerror = function (e) {
-                               console.log('server socket error');
+                               console.error('Server socket error');
                                socket.close();
                        };
                        socket.onclose = function () {
                                app.globalSocket = null;
                        };
-                       if (socket.peer.name !== '') {
-                               peerName = socket.peer.name;
-                       }
                };
        },
 
        onRegisterError: function onRegisterError() {
                "use strict";
-               console.log('Problem with server service registering');
        },
 
        registerServer: function registerServer() {
@@ -52,7 +47,7 @@ var server = {
                        try {
                                app.adapter.registerRFCOMMServiceByUUID(app.serviceUUID, 'Chat service', server.onRegisterSuccess, server.onRegisterError);
                        } catch (error) {
-                               console.log(error);
+                               console.log(error.message);
                        }
                }
        },
@@ -61,12 +56,14 @@ var server = {
                "use strict";
                try {
                        if (!app.adapter.visible) {
-                               app.adapter.setVisible(true, server.registerServer, function (error) { console.log(error); }, 0);
+                               app.adapter.setVisible(true, server.registerServer, function (error) {
+                                       console.error(error);
+                               }, 0);
                        } else {
                                server.registerServer();
                        }
                } catch (error) {
-                       console.log(error);
+                       console.error(error.message);
                }
        },
 
@@ -79,7 +76,6 @@ var server = {
 
        onUnregisterError: function onUnregisterError() {
                "use strict";
-               console.log('Problem with unregister server');
                app.numberOfClients = 0;
                app.restartBluetooth();
        },
@@ -95,5 +91,22 @@ var server = {
                } catch (error) {
                        server.onUnregisterError();
                }
+       },
+
+       /* WORKAROUND for the footer show when the soft keyboard is displayed */
+       showFooter: function showFooter(e) {
+               "use strict";
+               var page = $.mobile.activePage;
+               if (e.state === 'on') {
+                       page.find(":jqmData(role='footer')").show();
+                       e.stopPropagation();
+               }
+       },
+
+       /* WORKAROUND for the footer show when the soft keyboard is displayed */
+       enableFooterOnSoftKeyboard: function enableFooterOnSoftKeyboard() {
+               "use strict";
+               window.removeEventListener('softkeyboardchange', server.showFooter, false);
+               window.addEventListener('softkeyboardchange', server.showFooter, false);
        }
 };
\ No newline at end of file
diff --git a/templates/bye_popup.tpl b/templates/bye_popup.tpl
new file mode 100644 (file)
index 0000000..69bc1bf
--- /dev/null
@@ -0,0 +1,6 @@
+<div id="byePopup" data-role="popup" class="center_basic_2btn">
+       <div class="ui-popup-text" id="byeMessage"></div>
+       <div class="ui-popup-button-bg">
+               <a data-role="button" data-inline="true" id="byeOK">Ok</a>
+       </div>
+</div>
diff --git a/templates/chat_page.tpl b/templates/chat_page.tpl
new file mode 100644 (file)
index 0000000..0b4b14f
--- /dev/null
@@ -0,0 +1,20 @@
+<div id="chat" data-role="page" data-add-back-btn="header" data-footer-exist="true">
+       <div id="chat-header" data-role="header" data-position="fixed">
+               <h1><span id="chat-header-type"></span><span id="chat-header-name"></span></h1>
+       </div>
+
+       <div id="chat-content" data-role="content">
+               <ul data-role="listview"></ul>
+       </div>
+
+       <div id="chat-footer" data-role="footer" data-position="fixed">
+               <div id="ui-textArea">
+                       <div id="ui-textArea-text">
+                               <textarea id="text" placeholder="type new message" data-role="none"></textarea>
+                       </div>
+                       <div id="ui-textArea-button">
+                               <a data-role="button" id="ui-mySend">Send</a>
+                       </div>
+               </div>
+       </div>
+</div>
\ No newline at end of file
diff --git a/templates/choose_page.tpl b/templates/choose_page.tpl
new file mode 100644 (file)
index 0000000..fd8e31a
--- /dev/null
@@ -0,0 +1,12 @@
+<div data-role="page" id="choose" data-add-back-btn="footer" data-footer-exist="true">
+       <div data-role="header" id="choose-header" data-position="fixed">
+               <h1>Choose your server</h1>
+               <div data-role="progress" data-style="circle" id="discovering"></div>
+       </div>
+
+       <div data-role="content" id="choose-content">
+               <ul data-role="listview"></ul>
+       </div>
+
+       <div data-role="footer" data-position="fixed" id="choose-footer"></div>
+</div>
\ No newline at end of file
diff --git a/templates/keyboard_page.tpl b/templates/keyboard_page.tpl
new file mode 100644 (file)
index 0000000..ed229ab
--- /dev/null
@@ -0,0 +1,11 @@
+<div data-role="page" id="keyboard" data-add-back-btn="none">
+       <div data-role="header" id="keyboard-header" data-position="fixed">
+               <h1></h1>
+               <a data-role="button" id="keyboard-ok-button">OK</a>
+               <a data-role="button" id="keyboard-back-button">Back</a>
+       </div>
+
+       <div data-role="content" id="keyboard-content">
+               <input type="text" id="keyboard-text" maxlength="20"/>
+       </div>
+</div>
\ No newline at end of file
diff --git a/templates/left_bubble.tpl b/templates/left_bubble.tpl
new file mode 100644 (file)
index 0000000..2d20b1b
--- /dev/null
@@ -0,0 +1,3 @@
+<li class="ui-li-bubble-left">
+       %text%
+</li>
\ No newline at end of file
diff --git a/templates/right_bubble.tpl b/templates/right_bubble.tpl
new file mode 100644 (file)
index 0000000..507e30f
--- /dev/null
@@ -0,0 +1,3 @@
+<li class="ui-li-bubble-right">
+       %text%
+</li>
\ No newline at end of file
diff --git a/templates/server_row.tpl b/templates/server_row.tpl
new file mode 100644 (file)
index 0000000..7780cc4
--- /dev/null
@@ -0,0 +1,7 @@
+<li class="ui-li-has-multiline" address="%deviceAddress%" name="%deviceName%">
+       <a href="#">
+               <div class="server-row-name">%deviceName%</div>
+               <span class="ui-li-text-sub">%deviceAddress%</span>
+               <span class="ui-li-text-sub2"></span>
+       </a>
+</li>
\ No newline at end of file
diff --git a/templates/visibility_popup.tpl b/templates/visibility_popup.tpl
new file mode 100644 (file)
index 0000000..253c2d7
--- /dev/null
@@ -0,0 +1,8 @@
+<div id="visibilityPopup" data-role="popup" class="center_basic_2btn">
+       <div class="ui-popup-text">
+               Make your bluetooth radio visible
+       </div>
+       <div class="ui-popup-button-bg">
+               <a data-role="button" data-inline="true" id="visibilityOK">Ok</a>
+       </div>
+</div>