hwc-api.js

1       /*
2        * Sybase Hybrid App version 2.3.4
3        *
4        * hwc-api.js
5        * This file will not be regenerated, so it is possible to modify it, but it
6        * is not recommended.
7        *
8        * Copyright (c) 2011,2012 Sybase Inc. All rights reserved.
9        */
10      /** 
11       * Holds all the Hybrid Web Container javascript 
12       * @namespace 
13       */
14      hwc = (typeof hwc === "undefined" || !hwc) ? {} : hwc;      // SUP 'namespace'
15      
16      
17      /**
18       * Container API
19       */
20      (function(hwc, undefined) {
21      
22         /**
23          * Constant definitions for registration methods
24          */
25         /**
26          * Constant indicating no registration method preference. The application implementation decides the default method to use. 
27          * This is handled as Manual registration by the HWC. 
28          * Used in {@link hwc.ConnectionSettings}.
29          * @type number */
30         hwc.REGISTRATION_METHOD_NO_PREFERENCE = 0;
31         /**
32          * Constant indicating that automatic registration using password is the preferred method.  Used in {@link hwc.ConnectionSettings}.
33          * @type number */
34         hwc.REGISTRATION_METHOD_AUTOMATIC = 1;
35         /**
36          * Constant indicating that manual registration is the preferred method.  Used in {@link hwc.ConnectionSettings}.
37          * @type number */
38         hwc.REGISTRATION_METHOD_MANUAL = 2;
39         /**
40          * Constant indicating that automatic registration using a certificate from Afaria is the preferred method.  Used in {@link hwc.ConnectionSettings}.
41          * @type number */
42         hwc.REGISTRATION_METHOD_AFARIA = 3;
43         /**
44          * Constant indicating that automcatic registration using a local certificate is the preferred method.  Used in {@link hwc.ConnectionSettings}.
45          * @type number */
46         hwc.REGISTRATION_METHOD_CERTIFICATE = 4;
47      
48         /**
49          * Represents the connection settings for connecting to the SUP Server.  Used in {@link hwc.loadSettings} and {@link hwc.saveSettings}.
50          * 
51          * @classdesc
52          * @memberOf hwc
53          * @public
54          * @param {number} regmethod A number representing the registration method (must be one of {@link hwc.REGISTRATION_METHOD_NO_PREFERENCE}, {@link hwc.REGISTRATION_METHOD_MANUAL},
55          * {@link hwc.REGISTRATION_METHOD_AUTOMATIC}, {@link hwc.REGISTRATION_METHOD_AFARIA}, {@link hwc.REGISTRATION_METHOD_CERTIFICATE}).
56          * @param {string} server The SUP/Relay server name.
57          * @param {number} port The SUP/Relay server port number.
58          * @param {string} server The farm id.
59          * @param {string} user The user name.
60          * @param {string} activationcode The activation code.
61          * @param {string} protocol The protocol to use.  Must be "HTTP" or "HTTPS".
62          * @param {string} password The password for automatic registration.
63          * @param {string} urlsuffix The url suffix (used only when connecting to a relay server).
64          * @example
65          * // Create a new ConnectionSettings object.
66          * var connectionSettings = new hwc.ConnectionSettings( hwc.REGISTRATION_METHOD_MANUAL,
67          *                                            "999.999.999.999",
68          *                                            5001,
69          *                                            0,
70          *                                            "sampleUsername",
71          *                                            123,
72          *                                            "HTTP",
73          *                                            "samplePassword",
74          *                                            "/" );
75          * // Use the ConnectionSettings object we just created to set the connection settings.
76          * hwc.saveSettings( connectionSettings );
77          *
78          */
79         hwc.ConnectionSettings = function (regmethod, server, port, farm, user, activatecode, protocol, password, urlsuffix)
80         {
81            this.RegistrationMethod = regmethod;
82            this.ServerName = server;
83            this.Port = port;
84            this.FarmID = farm;
85            this.UserName = user;
86            this.ActivationCode = activatecode;
87            this.Protocol = protocol;
88            this.Password = password;
89            this.UrlSuffix = urlsuffix;
90         };
91      
92         /**
93          * Loads the current connection settings from the native application storage. 
94          * @memberOf hwc
95          * @public
96          * @returns {hwc.ConnectionSettings} The connection settings or null if there are no cached settings.
97          * @example
98          * // Load the connection settings.
99          * var connectionSettings = hwc.loadSettings();
100         */
101        hwc.loadSettings = function () {
102           var settings, response, jsonobj;
103           settings = null;
104           
105     	  hwc.traceEnteringMethod("hwc.loadSettings");
106           try {
107                  response = hwc.getDataFromContainer("loadsettings");
108                  jsonobj = JSON.parse(response);
109                  if (jsonobj !== null && jsonobj !== undefined) {
110                     settings = new hwc.ConnectionSettings(jsonobj.enableautoregistration, jsonobj.servername,
111                                                               jsonobj.port, jsonobj.farmid, jsonobj.username,
112                                                               jsonobj.activationcode, jsonobj.protocol, jsonobj.password,
113                                                               jsonobj.urlsuffix);
114     
115                 } 
116             }catch (ex){
117                 hwc.log("loadSettings error:" + ex.message, "ERROR", false);
118             } finally {
119     		    hwc.traceLeavingMethod("hwc.loadSettings");
120     		}
121     
122           return settings;
123        };
124     
125        /**
126         * Constant definitions for device management in add device registration.
127         * Some other error numbers may apply for technical support.
128         */
129        /**
130         * Constant indicating that MMS Authentication failed.  Possible return value for {@link hwc.saveSettings}.
131         * @type number */
132        hwc.REG_ERR_MMS_AUTHENTICATION_FAILED             = 14814;
133        /**
134         * Constant indicating that the connection to the MMS service failed.  Possible return value for {@link hwc.saveSettings}.
135         * @type number */
136        hwc.REG_ERR_COULD_NOT_REACH_MMS_SERVER            = 14813;
137        /**
138         * Constant indicating that no MBS template was found for given AppId and/or Security configuration.  Possible return value for {@link hwc.saveSettings}.
139         * @type number */
140        hwc.REG_ERR_AUTO_REG_TEMPLATE_NOT_FOUND           = 14850;
141        /**
142         * Constant indicating that auto registration was not enabled in the template.  Possible return value for {@link hwc.saveSettings}.
143         * @type number*/
144        hwc.REG_ERR_AUTO_REG_NOT_ENABLED                  = 14851;
145        /**
146         * Constant indicating that the given device id is already registered for another user.  Possible return value for {@link hwc.saveSettings}.
147         * @type number */
148        hwc.REG_ERR_AUTO_REG_WRONG_USER_FOR_DEVICE        = 14853;
149        /**
150         * Constant indicating that the user name is longer than the legal limit.  Possible return value for {@link hwc.saveSettings}.
151         * @type number */
152        hwc.REG_ERR_AUTO_REG_USER_NAME_TOO_LONG          = 14854;
153        /**
154         * Constant indicating that the user name contains invalid characters.  Possible return value for {@link hwc.saveSettings}.
155         * @type number */
156        hwc.REG_ERR_INVALID_USER_NAME                     = 14856;
157        /**
158         * Constant indicating {@link hwc.saveSettings} completed successfully.  Possible return value for {@link hwc.saveSettings}.
159         * @type number */
160        hwc.SETTING_SUCCESS                               = 0;
161     
162        /**
163         * Save the connection settings to native application storage.  
164         * Device registration will be attempted if and only the following conditions are both satisfied. 
165         * <ol>
166         * <li> The registration method is not manual. This can be passed in the hwc.ConnectionSettings object, or if that value is null, the currently configured value will be used. </li>
167         * <li> The password must be non-empty. This value MUST be passed in the hwc.ConnectionSettings object. </li>
168         * </ol>
169         * <p>
170         * <b> hwc.startClient() needs to be called after hwc.saveSettings() for the device to complete automatic/manual registration. </b>
171         * </p>
172         * <p>
173         * <b> Usage Note: </b> It is not mandatory to specify a value for each {@link  hwc.ConnectionSettings} property. Specifying a null or undefined for a {@link hwc.ConnectionSettings} 
174         * property will effectively cause this method to IGNORE the property and not change it's value. 
175         * </p>
176         * If the saveSettings() operation fails, a non-zero number will be returned. See hwc.REG_ERR_* for device registration errors.
177         * There can be other types of errors not listed here.
178         *
179         * @public
180         * @memberOf hwc
181         * @param {hwc.ConnectionSettings} settings The connection settings to be saved.
182         *
183         * @returns {number} A status code indicating success ({@link hwc.SETTING_SUCCESS}) or an error (one of {@link hwc.REG_ERR_AUTO_REG_NOT_ENABLED},
184         * {@link hwc.REG_ERR_AUTO_REG_TEMPLATE_NOT_FOUND}, {@link hwc.REG_ERR_AUTO_REG_USER_NAME_TOO_LONG}, {@link hwc.REG_ERR_AUTO_REG_WRONG_USER_FOR_DEVICE},
185         * {@link hwc.REG_ERR_COULD_NOT_REACH_MMS_SERVER}, {@link hwc.REG_ERR_INVALID_USER_NAME}, {@link hwc.REG_ERR_MMS_AUTHENTICATION_FAILED}).
186         * @example
187         * // Load the connection settings.
188         * var connectionSettings = hwc.loadSettings();
189         * // Modify the connection settings.
190         * connectionSettings.ServerName = "999.999.999.999";
191         * // Save the modified connection settings.
192         * hwc.saveSettings( connectionSettings );
193         * // Start the client to for the device to complete automatic/manual registration.
194         * hwc.startClient();
195         */
196        hwc.saveSettings = function (settings) {
197     	  hwc.traceEnteringMethod("hwc.saveSettings");
198           try {
199              // First compose the URL argument string
200              var argumentString, ret;
201              argumentString = "";
202     		 ret = "";
203              
204              if (settings.RegistrationMethod !== null && settings.RegistrationMethod !== undefined)
205              {
206                 argumentString = "&enableautoregistration=" + settings.RegistrationMethod;
207              }
208              if (settings.ServerName !== null && settings.ServerName !== undefined)
209              {
210                 argumentString = argumentString + "&servername=" + encodeURIComponent(settings.ServerName);
211              }
212              if (settings.Port !== null && settings.Port !== undefined)
213              {
214                 argumentString = argumentString + "&port=" + settings.Port;
215              }
216              if (settings.FarmID !== null && settings.FarmID !== undefined)
217              {
218                 argumentString = argumentString + "&farmid=" + encodeURIComponent(settings.FarmID);
219              }
220              if (settings.UserName !== null && settings.UserName !== undefined)
221              {
222                 argumentString = argumentString + "&username=" + encodeURIComponent(settings.UserName);
223              }
224              if (settings.ActivationCode !== null && settings.ActivationCode !== undefined)
225              {
226                 argumentString = argumentString + "&activationcode=" + encodeURIComponent(settings.ActivationCode);
227              }
228              if (settings.Protocol !== null && settings.Protocol !== undefined)
229              {
230                 argumentString = argumentString + "&protocol=" + encodeURIComponent(settings.Protocol);
231              }
232              if (settings.Password !== null && settings.Password !== undefined)
233              {
234                 argumentString = argumentString + "&password=" + encodeURIComponent(settings.Password);
235              }
236              if (settings.UrlSuffix !== null && settings.UrlSuffix !== undefined)
237              {
238                 argumentString = argumentString + "&urlsuffix=" + encodeURIComponent(settings.UrlSuffix);
239              }
240     
241              // Only invoke the native function if we're saving at least one setting
242              if (argumentString !== "")
243              {
244                 ret = hwc.getDataFromContainer("savesettings", argumentString);
245                 return parseInt(ret, 10);
246              }
247            else
248            {
249              return hwc.SETTING_SUCCESS;
250            }
251           } catch (ex){
252              hwc.log("saveSettings error:" + ex.message, "ERROR", false);
253              throw ex;
254           } finally {
255     		  hwc.traceLeavingMethod("hwc.saveSettings");
256     	  }
257        };
258     
259     
260        /**
261         * Start of connection state listener callback functions
262         */
263        /**
264         * An array of {@link anonymous.ConnectionStateListener} callback functions.
265         * @type Array
266         * @private
267         */
268        hwc._connectionListeners = [];
269        /**
270         * An array of objects containing {@link anonymous.ConnectionStateListener} callback functions.
271         * The containing objects need to be kept track of since the callback functions may reference
272         * variables in the containing object.
273         * @type Array
274         * @private
275         */
276        hwc._connectionListenerContainingObjects = [];
277     
278        /**
279         * This is the main entry of connection event notification. The native code
280         * calls this function internally
281         * @private
282         * @param {number} event A flag indicating the current connection state (will be either {@link hwc.CONNECTED} or {@link hwc.DISCONNECTED}).
283         * @param {number} errorCode An error code.  Will be 0 if there is no error.
284         * @param {string} errorMessage Text of an error message.  Will be the empty string if there is no error.
285         */
286        hwc.connectionListenerNotification = function (event, errorCode, errorMessage)
287        {
288           var i, containingObject;
289     	  hwc.traceEnteringMethod("hwc.connectionListenerNotification");
290           try {
291     		  if (hwc._connectionListeners.length === 0) {
292     			 return;
293     		  }
294     
295     		  for (i = 0; i < hwc._connectionListeners.length; i++)
296     		  {
297     			 containingObject = hwc._connectionListenerContainingObjects[i];
298     			 if (containingObject !== null && containingObject !== undefined)
299     			 {
300     				hwc._connectionListeners[i].call(containingObject, event, errorCode, errorMessage);
301     			 }
302     			 else
303     			 {
304     				hwc._connectionListeners[i](event, errorCode, errorMessage);
305     			 }
306     		  }
307     	  } finally {
308     		  hwc.traceLeavingMethod("hwc.connectionListenerNotification");
309     	  }
310        };
311     
312        /**
313         * Register the connection state listener.
314         *
315         * @public
316         * @memberOf hwc
317         * @param {anonymous.ConnectionStateListener} ConnectionStateListener Callback for connection state changes.
318         * @param {Object} [containingObject] Object containing definition for ConnectionStateListener.  If a connection state callback function
319         * references variables in its containing object, then the containing object should be passed to this function.
320         * @example
321         * // doSomething is a global function that gets called from the connection listener.
322         * var doSomething = function()
323         * {
324         *    alert("sample function that gets executed when the hwc becomes connected");
325         * }
326         * // connectionListener is the callback function that is given to addConnectionListener.
327         * // When there is a connection event, connectionListener will be invoked with the details.
328         * var connectionListener = function( event, errorCode, errorMessage )
329         * {
330         *    if( event == hwc.CONNECTED )
331         *    {
332         *       doSomething();
333         *    }
334         * }
335         * hwc.addConnectionListener( connectionListener );
336         *
337         * @example
338         * // connectionStateManager is an object that will contain the connection listener callback as well as
339         * // a variable used by the callback.
340         * var connectionStateManager = {};
341         * // The connectionStateManager keeps track of whether the HWC is connected or not.
342         * connectionStateManager.connected = false;
343         * // A function called by the listener.
344         * connectionStateManager.doSomething = function()
345         * {
346         *    if( this.connected )
347         *    {
348         *       alert("this alert gets displayed if the hwc is connected");
349         *    }
350         * }
351         * // This is the callback function that will be passed to addConnectionListener.  This callback references variables
352         * // from the containing object (this.connected and this.doSomething), so when we call addConnectionListener we have
353         * // to give the containing object as the second parameter.
354         * connectionStateManager.listener = function( event, errorCode, errorMessage )
355         * {
356         *    if( event == hwc.CONNECTED )
357         *    {
358         *       this.connected = true;
359         *    }
360         *    else
361         *    {
362         *       this.connected = false;
363         *    }
364         *    this.doSomething();
365         * }
366         * // Pass both the listener and the containing object.  This enables the listener to refer to variables in the containing object when it is invoked.
367         * hwc.addConnectionListener( connectionStateManager.listener, connectionStateManager );
368         */
369        hwc.addConnectionListener = function (ConnectionStateListener, containingObject)
370        {
371     	  hwc.traceEnteringMethod("hwc.addConnectionListener");
372     	  try {
373     		  hwc._connectionListeners.push(ConnectionStateListener);
374     		  hwc._connectionListenerContainingObjects.push(containingObject);
375     		  if (hwc._connectionListeners.length === 1)
376     		  {
377     			 hwc.getDataFromContainer("startconnectionlistener");
378     		  }
379     	  } finally {
380     		  hwc.traceLeavingMethod("hwc.addConnectionListener");
381     	  }
382        };
383     
384         /**
385         * Remove the connection state listener.  This function should be called with identical parameters that were used
386         * when adding the connection state listener with {@link hwc.addConnectionListener}.
387         *
388         * @public
389         * @memberOf hwc
390         * @param {anonymous.ConnectionStateListener} ConnectionStateListener Callback function with connection state changes
391         * @param {Object} [containingObject] Optional Object containing definition of ConnectionStateListener
392         * @example
393         * // doSomething is a global function that gets called from the connection listener.
394         * var doSomething = function()
395         * {
396         *    alert("sample function that gets executed when the hwc becomes connected");
397         * }
398         * // connectionListener is the callback function that is given to addConnectionListener.
399         * // When there is a connection event, connectionListener will be invoked with the details.
400         * var connectionListener = function( event, errorCode, errorMessage )
401         * {
402         *    if( event == hwc.CONNECTED )
403         *    {
404         *       doSomething();
405         *    }
406         * }
407         * hwc.addConnectionListener( connectionListener );
408         * // At some other point if we want to remove the listener, we use the following line:
409         * hwc.removeConnectionListener( connectionListener );
410         *
411         * @example
412         * // connectionStateManager is an object that will contain the connection listener callback as well as
413         * // a variable used by the callback.
414         * var connectionStateManager = {};
415         * // The connectionStateManager keeps track of whether the HWC is connected or not.
416         * connectionStateManager.connected = false;
417         * // A function called by the listener.
418         * connectionStateManager.doSomething = function()
419         * {
420         *    if( this.connected )
421         *    {
422         *       alert("this alert gets displayed if the hwc is connected");
423         *    }
424         * }
425         * // This is the callback function that will be passed to addConnectionListener.  This callback references variables
426         * // from the containing object (this.connected and this.doSomething), so when we call addConnectionListener we have
427         * // to give the containing object as the second parameter.
428         * connectionStateManager.listener = function( event, errorCode, errorMessage )
429         * {
430         *    if( event == hwc.CONNECTED )
431         *    {
432         *       this.connected = true;
433         *    }
434         *    else
435         *    {
436         *       this.connected = false;
437         *    }
438         *    this.doSomething();
439         * }
440         * // Pass both the listener and the containing object.  This enables the listener to refer to variables in the containing object when it is invoked.
441         * hwc.addConnectionListener( connectionStateManager.listener, connectionStateManager );
442         * // At some other point if we want to remove the listener, we use the following line:
443         * hwc.removeConnectionListener( connectionStateManager.listener, connectionStateManager );
444         */
445        hwc.removeConnectionListener = function (ConnectionStateListener, containingObject)
446        {
447           var i;
448     	  hwc.traceEnteringMethod("hwc.removeConnectionListener");
449     	  try {
450     		  if (hwc._connectionListeners.length === 0) {
451     			 return;
452     		  }
453     
454     		  for (i = 0; i < hwc._connectionListeners.length; i++)
455     		  {
456     			 if (hwc._connectionListeners[i] === ConnectionStateListener &&
457     				 hwc._connectionListenerContainingObjects[i] === containingObject)
458     			 {
459     				hwc._connectionListeners.splice(i, 1);
460     				hwc._connectionListenerContainingObjects.splice(i, 1);
461     				if (hwc._connectionListeners.length === 0)
462     				{
463     				   hwc.getDataFromContainer("stopconnectionlistener");
464     				}
465     				return;
466     			 }
467     		  }
468     	  } finally {
469     		  hwc.traceLeavingMethod("hwc.removeConnectionListener");
470     	  }
471         };
472     
473         /**
474         * A sample {@link anonymous.ConnectionStateListener} callback function.
475         *
476         * @param {number} event A number indicating the event that occurred (will be {@link hwc.CONNECTED} or {@link hwc.DISCONNECTED}).
477         * @param {number} errorCode An error code (0 indicating success).
478         * @param {string} errorMessage Text of the error message.  Will be empty of there is no error.
479         */
480        hwc.sample_ConnectionListener = function (event, errorCode, errorMessage) {
481           switch (event)
482           {
483              case hwc.CONNECTED:
484                 alert('Connected event');
485                 break;
486              case hwc.DISCONNECTED:
487                 alert('Disconnected event');
488                 break;
489           }
490     
491           if (errorCode !== null && errorMessage !== null)
492           {
493              alert('Connection error\n' +
494                    'Code: ' + errorCode + '\n' +
495                    'Message: ' + errorMessage);
496           }
497        };
498     
499        /** 
500         * Constant indicating that the hwc is connected.  Used in {@link anonymous.ConnectionStateListener} callback functions.
501         * @type number
502         */
503        hwc.CONNECTED = 1;
504        /**
505         * Constant indicating that the hwc is disconnected.  Used in {@link anonymous.ConnectionStateListener} callback functions.
506         * @type number
507         */
508        hwc.DISCONNECTED = 2;
509     
510     
511        /**
512         * Start the client connection to the SUP server.  Companion function to {@link hwc.shutdown}.
513         * If a hybrid app is running in the context of the Hybrid Web Container
514         * then it will probably never have to call this function unless {@link hwc.shutdown} client was called first.
515         *
516         * @public
517         * @memberOf hwc
518         * @param {anonymous.LogListener} [onNotification] A log listener callback function.  If you are interested in
519         * the connection state it is recommended that you call {@link hwc.addConnectionListener} before calling hwc.startClient.
520         * @example
521         * hwc.startClient();
522         *
523         * @example
524         * // Add a log listener while calling hwc.startClient.
525         * var logListener = function( time, event, message )
526         * {
527         *    alert(message);
528         * }
529         * hwc.startClient( logListener );
530         */
531        hwc.startClient = function (onNotification) {
532     	  hwc.traceEnteringMethod("hwc.startClient");
533           try {
534              if (hwc._defaultLogListener !== null && hwc._defaultLogListener !== undefined)
535              {
536                 hwc.removeLogListener(hwc._defaultLogListener, null);
537                 hwc._defaultLogListener = null;
538              }
539     
540              if (onNotification !== null && onNotification !== undefined)
541              {
542                 hwc.addLogListener( onNotification, null );
543                 hwc._defaultLogListener = onNotification;
544              }
545     
546              hwc.getDataFromContainer( "startclient" );
547              return 0;
548           } catch (ex){
549             hwc.log("startClient error:" + ex.message, "ERROR", false);
550           } finally {
551     		hwc.traceLeavingMethod("hwc.startClient");
552     	  }
553        };
554     
555        /**
556         * Shutdown the client connection to the SUP server.  Companion function to {@link hwc.startClient}.  
557         * If a hybrid app is running in the context of the Hybrid Web Container, then it will probably never have to call
558         * this function.  If you want to temporarily stop the connection, then call {@link hwc.disconnectFromServer} instead.
559         * @public
560         * @memberOf hwc
561         * @example
562         * hwc.shutdown();
563         */
564        hwc.shutdown = function () {
565     	  hwc.traceEnteringMethod("hwc.shutdown");
566           try {
567              hwc.getDataFromContainer("shutdownclient");
568     
569              if (hwc._defaultLogListener !== null && hwc._defaultLogListener !== undefined)
570              {
571                 hwc.removeLogListener(hwc._defaultLogListener, null);
572                 hwc._defaultLogListener = null;
573              }
574           } catch (ex){
575             hwc.log("shutdown error:" + ex.message, "ERROR", false);
576           } finally {
577     		  hwc.traceLeavingMethod("hwc.shutdown");
578     	  }
579        };
580     
581        /**
582         * Resumes the connection to the SUP server.  Companion function to {@link hwc.disconnectFromServer}.  This function should
583         * only be called after the connection to the SUP server has been suspened with a call to {@link hwc.disconnectFromServer}.
584         *
585         * @public
586         * @memberOf hwc
587         * @param {anonymous.LogListener} [onNotification] A log listener callback function.  If you are interested in
588         * the connection state it is recommended that you call {@link hwc.addConnectionListener} before calling hwc.connectToServer.
589         *
590         * @example
591         * hwc.connectToServer();
592         *
593         * @example
594         * // Add a log listener while calling hwc.connectToServer.
595         * var logListener = function( time, event, message )
596         * {
597         *    alert(message);
598         * }
599         * hwc.connectToServer( logListener );
600         */
601        hwc.connectToServer = function (onNotification) {
602     	  hwc.traceEnteringMethod("hwc.connectToServer");
603           try {
604              if (hwc._defaultLogListener !== null && hwc._defaultLogListener !== undefined)
605              {
606                 hwc.removeLogListener(hwc._defaultLogListener, null);
607                 hwc._defaultLogListener = null;
608              }
609     
610              if (onNotification !== null && onNotification !== undefined)
611              {
612                 hwc.addLogListener( onNotification, null );
613                 hwc._defaultLogListener = onNotification;
614              }
615     
616              hwc.getDataFromContainer( "connecttoserver" );
617     
618              return 0;
619           } catch (ex){
620              hwc.log("connectToServer error:" + ex.message, "ERROR", false);
621              throw ex;
622           } finally {
623     		  hwc.traceLeavingMethod("hwc.connectToServer");
624     	  }
625        };
626     
627        /**
628         * This is the default one to keep the listener added in the connectionToServer call.
629         * @private
630         */
631        hwc._defaultLogListener = null;
632     
633        /**
634         * Suspends the connection to the SUP server.  Companion function to {@link hwc.connectToServer}.
635         * @public
636         * @memberOf hwc
637         * @example
638         * hwc.disconnectFromServer();
639         */
640        hwc.disconnectFromServer = function () {
641     	  hwc.traceEnteringMethod("hwc.disconnectFromServer");
642           try {
643              hwc.getDataFromContainer("disconnectfromserver");
644     
645              if (hwc._defaultLogListener !== null && hwc._defaultLogListener !== undefined)
646              {
647                 hwc.removeLogListener(hwc._defaultLogListener, null);
648                 hwc._defaultLogListener = null;
649              }
650     
651           } catch (ex){
652             hwc.log("disconnectFromServer error:" + ex.message, "ERROR", false);
653           } finally {
654     		  hwc.traceLeavingMethod("hwc.disconnectFromServer");
655     	  }
656        };
657     
658        /**
659         * Start of connection functions
660         */
661     
662        /**
663         * An array of log listener callback functions.
664         * @type Array
665         * @private
666         */
667        hwc._logListeners = [];
668        /**
669         * An array of objects containing log listener callback functions.  The containing objects
670         * need to be kept track of because the callback functions may reference variables in the
671         * containing object.
672         * @type Array
673         * @private
674         */
675        hwc._logListenerContainingObjects = [];
676     
677        /**
678         * This is the main entry of log event notification. The native code
679         * calls this function internally.
680         *
681         * @param {number} milliseconds The date of the log message represented in milliseconds.
682         * @param {number} event The that represents which category this event falls under (It will be one of hwc.CONNECTION_* constants).
683         * @param {string} optionalString The string carrying the message of the log event.
684     	* @private
685         */
686        hwc._logListenerNotification = function ( milliseconds, event, optionalString )
687        {
688           var date, i, containingObject;
689     	  hwc.traceEnteringMethod("hwc._logListenerNotification");
690     	  try {
691     		  if (hwc._logListeners.length === 0) {
692     			return;
693     		  }
694     
695     		  // The incoming date is number of millisecond, we need to change it to real JavaScript Date type.
696     		  date = new Date(milliseconds);
697     
698     		  for (i = 0; i < hwc._logListeners.length; i++)
699     		  {
700     			 containingObject = hwc._logListenerContainingObjects[i];
701     			 if (containingObject !== null && containingObject !== undefined)
702     			 {
703     				hwc._logListeners[i].call(containingObject, date, event, optionalString);
704     			 }
705     			 else
706     			 {
707     				hwc._logListeners[i](date, event, optionalString);
708     			 }
709     		  }
710     	  } finally {
711     		  hwc.traceLeavingMethod("hwc._logListenerNotification");
712     	  }
713        };
714     
715        /**
716         * Register the log listener.
717         * @public
718         * @memberOf hwc
719         * @param {anonymous.LogListener} LogListener Callback for changes to the log.
720         * @param {Object} [containingObject] Object containing definition for LogListener.  If a log listener callback function
721         * references variables in its containing object, then the containing object should be passed to this function.
722         *
723         * @example
724         * // A global function called by the log listener.
725         * var doSomething = function()
726         * {
727         *    alert("this gets displays when there is a log event.");
728         * }
729         * // The log listener callback function that will be passed to hwc.addLogListener.
730         * // This function will be invoked whenever there is a log event.
731         * var logListener = function( event, errorCode, errorMessage )
732         * {
733         *    doSomething();
734         * }
735         * // Add the log listener.
736         * hwc.addLogListener( logListener );
737         *
738         * @example
739         * // logListenerManager is an object that will contain the listener callback as well
740         * // as a function that will be invoked from the listener callback function.
741         * var logListenerManager = {};
742         * // This is a function that is called from the listener callback.
743         * logListenerManager.doSomething = function()
744         * {
745         *    alert("this gets displays when there is a log event.");
746         * }
747         * // This is the listener callback that will be passed to hwc.addLogListener.
748         * // Since a variable is referenced from the containing object, the containing object
749         * // will need to be passed to hwc.addLogListener.
750         * logListenerManager.listener = function( event, errorCode, errorMessage )
751         * {
752         *    this.doSomething();
753         * }
754         * // Pass both the listener callback and the containing object.
755         * hwc.addLogListener( logListenerManager.listener, logListenerManager );
756         */
757        hwc.addLogListener = function ( LogListener, containingObject)
758        {
759     	  hwc.traceEnteringMethod("hwc.addLogListener");
760     	  try {
761     		  hwc._logListeners.push(LogListener);
762     		  hwc._logListenerContainingObjects.push(containingObject);
763     		  if (hwc._logListeners.length === 1)
764     		  {
765     			 hwc.getDataFromContainer("startloglistener");
766     		  }
767     	  } finally {
768     		  hwc.traceLeavingMethod("hwc.addLogListener");
769     	  }
770        };
771     
772        /**
773         * Remove the log listener.  This function should be called with identical parameters that were used
774         * when adding the log listener with {@link hwc.addLogListener}.
775         *
776         * @public
777         * @memberOf hwc
778         * @param {anonymous.LogListener} LogListener The callback function for log events.
779         * @param {Object} [containingObject] Object containing definition of ConnectionStateListener
780         * @example
781         * // A global function called by the log listener.
782         * var doSomething = function()
783         * {
784         *    alert("this gets displays when there is a log event.");
785         * }
786         * // The log listener callback function that will be passed to hwc.addLogListener.
787         * // This function will be invoked whenever there is a log event.
788         * var logListener = function( event, errorCode, errorMessage )
789         * {
790         *    doSomething();
791         * }
792         * // Add the log listener.
793         * hwc.addLogListener( logListener );
794         * // at some other point if we want to remove the listener, we use the following line
795         * hwc.removeLogListener( logListener );
796         *
797         * @example
798         * // logListenerManager is an object that will contain the listener callback as well
799         * // as a function that will be invoked from the listener callback function.
800         * var logListenerManager = {};
801         * // This is a function that is called from the listener callback.
802         * logListenerManager.doSomething = function()
803         * {
804         *    alert("this gets displays when there is a log event.");
805         * }
806         * // This is the listener callback that will be passed to hwc.addLogListener.
807         * // Since a variable is referenced from the containing object, the containing object
808         * // will need to be passed to hwc.addLogListener.
809         * logListenerManager.listener = function( event, errorCode, errorMessage )
810         * {
811         *    this.doSomething();
812         * }
813         * // Pass both the listener callback and the containing object.
814         * hwc.addLogListener( logListenerManager.listener, logListenerManager );
815         * // at some other point if we want to remove the listener, we use the following line
816         * hwc.removeLogListener( logListenerManager.listener, logListenerManager );
817         */
818        hwc.removeLogListener = function (LogListener, containingObject)
819        {
820           var i;
821     	  hwc.traceEnteringMethod("hwc.removeLogListener");
822     	  try {
823     		  if (hwc._logListeners.length === 0){
824     			 return;
825     		  }
826     
827     		  for (i = 0; i < hwc._logListeners.length; i++)
828     		  {
829     			 if (hwc._logListeners[i] === LogListener &&
830     				hwc._logListenerContainingObjects[i] === containingObject)
831     			 {
832     				hwc._logListeners.splice(i, 1);
833     				hwc._logListenerContainingObjects.splice(i, 1);
834     
835     				if (hwc._logListeners.length === 0)
836     				{
837     				   hwc.getDataFromContainer("stoploglistener");
838     				}
839     				return;
840     			 }
841     		  }
842     	  } finally {
843     		  hwc.traceLeavingMethod("hwc.removeLogListener");
844     	  }
845        };
846     
847        /**
848         * Sample {@link anonymous.LogListener} callback function.
849         *
850         * @param {number} milliseconds The date of the log message represented in milliseconds.
851         * @param {number} event The that represents which category this event falls under (It will be one of {@link hwc.CONNECTION_ERROR},
852         * {@link hwc.CONNECTION_OTHER}, {@link hwc.CONNECTION_CONNECTED}, {@link hwc.CONNECTION_DISCONNECTED}, {@link hwc.CONNECTION_RETRIEVED_ITEMS}).
853         * @param {string} optionalString The string carrying the message of the log event.
854         */
855        hwc.sample_LogListener = function ( date, event, optionalString ) {
856        };
857     
858        // Connection event definitions
859        /**
860         * A constant indicating that the log message is about a connection error.  Used in {@link anonymous.LogListener} callback functions.
861         * @type number
862         */
863        hwc.CONNECTION_ERROR = -1;
864        /**
865         * A constant indicating that the log message is not about the connection.  Used in {@link anonymous.LogListener} callback functions.
866         * @type number
867         */
868        hwc.CONNECTION_OTHER = 0;
869        /**
870         * A constant indicating that the log message is about the connection being established.  Used in {@link anonymous.LogListener} callback functions.
871         * @type number
872         */
873        hwc.CONNECTION_CONNECTED = 1;
874        /**
875         * A constant indicating that the log message is about the connection being disconnected.  Used in {@link anonymous.LogListener} callback functions.
876         * @type number
877         */
878        hwc.CONNECTION_DISCONNECTED = 2;
879        /**
880         * a constant indicating that the log message is about retrieved items.  Used in {@link anonymous.LogListener} callback functions.
881         * @type number
882         */
883        hwc.CONNECTION_RETRIEVED_ITEMS = 3;
884     
885     
886        /**
887         * Start of hybrid app installation callback functions
888         */
889     
890        /**
891         * An array of app installation listeners
892         * @private
893         * @type Array
894         */
895        hwc._appInstallationListeners = [];
896     
897        /**
898         * This is the main entry of installation notification. The native code should be
899         * hardcoded to call this function internally.
900         *
901         * @private
902         * @param {number} event A constant indicating whether the app installation is beginning or has just ended
903         * (will be either {@link hwc.INSTALLATION_BEGIN} or {@link hwc.INSTALLATION_END}).
904         * @param {number} moduleId The module ID of the hybrid app being installed.
905         * @param {number} version The version of the hybrid app being installed.
906         * @param {string} moduleName The display name of the hybrid app being installed.
907         */
908        hwc.appInstallationListenerNotification = function (event, moduleId, version, moduleName)
909        {
910           var i;
911     	  hwc.traceEnteringMethod("hwc.appInstallationListenerNotification");
912     	  try {
913     		  if (hwc._appInstallationListeners.length === 0) {
914     			 return;
915     		  }
916     
917     		  for (i = 0; i < hwc._appInstallationListeners.length; i++)
918     		  {
919     			 hwc._appInstallationListeners[i](event, moduleId, version, moduleName);
920     		  }
921     	  } finally {
922     		  hwc.traceLeavingMethod("hwc.appInstallationListenerNotification");
923     	  }
924        };
925     
926        /**
927         * Register the application installation listener.
928         *
929         * @param {anonymous.AppInstallationListener} AppInstallationListener A callback for application installation changes.
930         *
931         * @example
932         * // appInstallListener is the callback function that will be passed to hwc.addAppInstallationListener.
933         * var appInstallListener = function( event, moduleId, version, moduleName )
934         * {
935         *    if( event == hwc.INSTALLATION_BEGIN )
936         *    {
937         *       alert(moduleName + " has just started the installation process.");
938         *    }
939         *    else if( event == hwc.INSTALLATION_END )
940         *    {
941         *       alert(moduleName + " has just finished the installation process.");
942         *    }
943         * }
944         * hwc.addAppInstallationListener( appInstallListener );
945         */
946        hwc.addAppInstallationListener = function (AppInstallationListener)
947        {
948     	  hwc.traceEnteringMethod("hwc.addAppInstallationListener");
949     	  try {
950     		  hwc._appInstallationListeners.push(AppInstallationListener);
951     		  if(hwc._appInstallationListeners.length === 1)
952     		  {
953     			 hwc.getDataFromContainer("startAppInstallationListener");
954     		  }
955     	  } finally {
956     		  hwc.traceLeavingMethod("hwc.addAppInstallationListener");
957     	  }
958        };
959     
960        /**
961         * Remove the application installation listener.  This function should be called with identical parameters
962         * that were used to add the application installation listener with {@link hwc.addAppInstallationListener}.
963         *
964         * @public
965         * @memberOf hwc
966         * @param {anonymous.AppInstallationListener} AppInstallationListener The callback for application installation changes.
967         * @example
968         * // appInstallListener is the callback function that will be passed to hwc.addAppInstallationListener.
969         * var appInstallListener = function( event, moduleId, version, moduleName )
970         * {
971         *    if( event == hwc.INSTALLATION_BEGIN )
972         *    {
973         *       alert(moduleName + " has just started the installation process.");
974         *    }
975         *    else if( event == hwc.INSTALLATION_END )
976         *    {
977         *       alert(moduleName + " has just finished the installation process.");
978         *    }
979         * }
980         * hwc.addAppInstallationListener( appInstallListener );
981         * // when we want to remove this listener, we call the following line:
982         * hwc.removeAppInstallationListener( appInstallListener );
983         */
984        hwc.removeAppInstallationListener = function (AppInstallationListener)
985        {
986           var i;
987     	  hwc.traceEnteringMethod("hwc.removeAppInstallationListener");
988     	  try {
989     		  if (hwc._appInstallationListeners.length === 0) {
990     			 return;
991     		  }
992     
993     		  for (i = 0; i < hwc._appInstallationListeners.length; i++)
994     		  {
995     			 if (hwc._appInstallationListeners[i] === AppInstallationListener)
996     			 {
997     				hwc._appInstallationListeners.splice(i, 1);
998     				break;
999     			 }
1000    		  }
1001    
1002    		  if (hwc._appInstallationListeners.length === 0)
1003    		  {
1004    			 hwc.getDataFromContainer("stopAppInstallationListener");
1005    		  }
1006    		  
1007    	  } finally {
1008    		  hwc.traceLeavingMethod("hwc.removeAppInstallationListener");
1009    	  }
1010       };
1011    
1012    	/**
1013        * Sample application listener callback function
1014        * @param {Integer} event            Installation flags including, BEGIN(1), END(2), FAIL(3)
1015        * @param {String} moduleId          Optional Module Id
1016        * @param {String} version           Optional Module version
1017    	* @param {String} moduleName        Optional Module display name
1018       	* @param {String} designerVersion   Optional Version of designer used to create app
1019       	* @param {String} containerVersion  Optional Version of hybrid web container
1020        */
1021       hwc.sample_InstallationAppListener = function (event, moduleId, version, moduleName, designerVersion, containerVersion) {
1022       };
1023    
1024       // Installation event definitions
1025       /**
1026        * A constant indicating that the application is starting to be installed.  Used in {@link anonymous.AppInstallationListener} callback functions.
1027        * @type number
1028        */
1029       hwc.INSTALLATION_BEGIN = 1;
1030       /**
1031        * A constant indicating that the application has finished being installed.  Used in {@link anonymous.AppInstallationListener} callback functions.
1032        * @type number
1033        */
1034       hwc.INSTALLATION_END = 2;
1035       hwc.INSTALLATION_FAIL = 3;
1036    
1037       /**
1038        * Call this function to get an array of {@link hwc.LogEntry} objects.  There will be one
1039        * {@link hwc.LogEntry} object for each line in the HWC log.
1040        *
1041        * @public
1042        * @memberOf hwc
1043        * @returns {hwc.LogEntry[]} An array of hwc.LogEntry objects.
1044        * @example
1045        * var log = hwc.getLogEntries();
1046        */
1047       hwc.getLogEntries = function () {
1048          var response, logEntries, i, entries, entry;
1049          
1050    	  hwc.traceEnteringMethod("hwc.getLogEntries");
1051          response = "";
1052          logEntries = [];
1053          
1054          try {
1055             response = hwc.getDataFromContainer("getlogentries");
1056    
1057             if (response !== null && response !== undefined && response !== "")
1058             {
1059                entries = JSON.parse(response);
1060                for (i=0; i<entries.length; i++) {
1061                   entry = entries[i];
1062                   logEntries[i] = new hwc.LogEntry(new Date(entry.milliseconds), entry.event, entry.message);
1063                }
1064             }
1065          } catch (ex){
1066            hwc.log("getLogEntries error:" + ex.message, "ERROR", false);
1067          } finally {
1068    		  hwc.traceLeavingMethod("hwc.getLogEntries");
1069    	  }
1070    
1071          return logEntries;
1072       };
1073    
1074       /**
1075        * This object represents a log entry.
1076        * @classdesc
1077        * @public
1078        * @memberOf hwc
1079        * @param {number} date The date the log entry was recorded, in milliseconds since January 1, 1970, 00:00:00 GMT
1080        * @param {number} event The event ID of the log entry (will be one of {@link hwc.CONNECTION_ERROR}, {@link hwc.CONNECTION_OTHER},
1081        * {@link hwc.CONNECTION_CONNECTED}, {@link hwc.CONNECTION_DISCONNECTED}, {@link hwc.CONNECTION_RETRIEVED_ITEMS})
1082        * @param {string} msg The message of the log entry.
1083        */
1084       hwc.LogEntry = function (date, event, msg)
1085       {
1086          this.logdate = date;
1087          this.eventID = event;
1088          this.message = msg;
1089    
1090          /**
1091           * Gets the date of the log entry.
1092           * @public
1093           * @memberOf hwc.LogEntry
1094           * @returns {number} The date the log entry was created in the HWC, in milliseconds.
1095           */
1096          this.getDate = function ()
1097          {
1098             return this.logdate;
1099          };
1100    
1101          /**
1102           * Gets the event ID of the log entry to see what this log entry is about.
1103           * @public
1104           * @memberOf hwc.LogEntry
1105           * @returns {number} A constant indication what this log entry is about (will be one of {@link hwc.CONNECTION_ERROR}, {@link hwc.CONNECTION_OTHER},
1106           * {@link hwc.CONNECTION_CONNECTED}, {@link hwc.CONNECTION_DISCONNECTED}, {@link hwc.CONNECTION_RETRIEVED_ITEMS}).
1107           */
1108          this.getEventID = function ()
1109          {
1110             return this.eventID;
1111          };
1112    
1113          /**
1114           * Gets the message text of the log entry.
1115           * @public
1116           * @memberOf hwc.LogEntry
1117           * @returns {string} The message text of the log entry.
1118           */
1119          this.getMessage = function ()
1120          {
1121             return this.message;
1122          };
1123       };
1124    
1125        /**
1126         * An array of push notification listeners
1127         * @private
1128         * @type Array
1129         */
1130        hwc._pushnotificationlisteners = [];
1131        /**
1132         * An array of objects containing push notification listeners
1133         * @private
1134         * @type Array
1135         */
1136        hwc._pushnotificationlistenerContainingObjects = [];
1137    
1138        /**
1139        * This is the main entry of push notification. The native code
1140        * calls this function internally.
1141        * @private
1142        * @param {string} jsonString      The notifications in JSON encoding
1143        * @param {Integer} [id]           ID of the communication area if required
1144        */
1145        hwc._pushnotificationListenerNotification = function(jsonString, id)
1146        {
1147            var ret, i, notifications, containingObject;
1148    		
1149    	    hwc.traceEnteringMethod("hwc._pushnotificationListenerNotification");
1150    		try {
1151    			ret = hwc.NOTIFICATION_CONTINUE;
1152    			try
1153    			{
1154    				if (hwc._pushnotificationlisteners.length > 0) {
1155    					notifications = JSON.parse(jsonString);
1156    					// We must have a valid push data to continue
1157    					if (!(notifications === null || notifications === undefined || notifications.length === 0))
1158    					{
1159    						for (i = 0; i < hwc._pushnotificationlisteners.length; i++)
1160    						{
1161    							try
1162    							{
1163    								ret = hwc.NOTIFICATION_CONTINUE; // default status
1164    
1165    								containingObject = hwc._pushnotificationlistenerContainingObjects[i];
1166    								if (containingObject !== null && containingObject !== undefined)
1167    								{
1168    									ret = hwc._pushnotificationlisteners[i].call(containingObject, notifications);
1169    								}
1170    								else
1171    								{
1172    									ret = hwc._pushnotificationlisteners[i](notifications);
1173    								}
1174    
1175    								// If the return status is hwc.NOTIFICATION_CANCEL, we need to return immediately.
1176    								if (ret === hwc.NOTIFICATION_CANCEL) {
1177    									break;
1178    								}
1179    							}
1180    							catch (ex)
1181    							{
1182    								// Don't pop alert here because it will block the whole process of notifications
1183    							}
1184    						}  //for
1185    					} //if
1186    				} //if
1187    			}
1188    			catch (ex1)
1189    			{
1190    				// Don't pop alert here because it will block the whole process of notifications
1191    			}
1192    			if (hwc.isBlackBerry() || hwc.isIOS() )
1193    			{
1194    				return ret;
1195    			}
1196    			else
1197    			{
1198    				hwc.getDataFromContainer("jsmethodreturn", "&id=" + id + "&jsreturnvalue=" + ret);
1199    			}
1200    			
1201    		} finally {
1202    			hwc.traceLeavingMethod("hwc._pushnotificationListenerNotification");
1203    		}
1204        };
1205    
1206        /**
1207        * Register a push notification listener.
1208        *
1209        * @public
1210        * @memberOf hwc
1211        * @param {function} PushNotificationListener The callback for push notifications.
1212        * @param {Object} [containingObject] Object containing definition for PushNotificationListener.  If the listener callback function
1213        * references variables in its containing object, then the containing object should be passed to this function.
1214        * @example
1215        * // pushListener is the callback function that will be passed to hwc.addPushNotificationListener.
1216        * var pushListener = function( notifications )
1217        * {
1218        *    alert( "push notification:\n" + JSON.stringify(notifications) );
1219        *    return hwc.NOTIFICATION_CONTINUE;
1220        * }
1221        * hwc.addPushNotificationListener( pushListener );
1222        *
1223        * @example
1224        * // pushListenerManager is an object that will contain the listener callback as well as a variable
1225        * // referenced from the callback.
1226        * var pushListenerManager = {};
1227        * // doSomething is a function that is called from inside the callback.
1228        * pushListenerManager.doSomething = function( notifications )
1229        * {
1230        *    alert( "push notification:\n" + JSON.stringify(notifications) );
1231        *    return hwc.NOTIFICATION_CONTINUE;
1232        * }
1233        * // This is the callback function.
1234        * pushListenerManager.listener = function( notifications )
1235        * {
1236        *    return this.doSomething( notifications );
1237        * }
1238        * // Since the callback function references variables in its containing object, the containing object
1239        * // must be passed to hwc.addPushNotificationListener as well.
1240        * hwc.addPushNotificationListener( pushListenerManager.listener, pushListenerManager );
1241        */
1242        hwc.addPushNotificationListener = function(PushNotificationListener, containingObject)
1243        {
1244    	    hwc.traceEnteringMethod("hwc.addPushNotificationListener");
1245    		try {
1246    			hwc._pushnotificationlisteners.push(PushNotificationListener);
1247    			hwc._pushnotificationlistenerContainingObjects.push(containingObject);
1248    			// The native side will start to notify the notification when the first
1249    			// listener is added
1250    			if (hwc._pushnotificationlisteners.length === 1)
1251    			{
1252    				hwc.getDataFromContainer("startpushnotificationlistener");
1253    			}
1254    		} finally {
1255    			hwc.traceLeavingMethod("hwc.addPushNotificationListener");
1256    		}
1257        };
1258    
1259        /**
1260        * Remove the push notification listener.  This function should be called with identical parameters that were used
1261        * to add the push notification listener with {@link hwc.addPushNotificationListener}.
1262        *
1263        * @public
1264        * @memberOf hwc
1265        * @param {anonymous.PushNotificationListener} PushNotificationListener The callback for push notifications.
1266        * @param {Object} [containingObject] The containing object of the listener.
1267        * @example
1268        * // pushListener is the callback function that will be passed to hwc.addPushNotificationListener.
1269        * var pushListener = function( notifications )
1270        * {
1271        *    alert( "push notification:\n" + JSON.stringify(notifications) );
1272        *    return hwc.NOTIFICATION_CONTINUE;
1273        * }
1274        * hwc.addPushNotificationListener( pushListener );
1275        * // At some other point if we want to remove the push listener, we call the following line:
1276        * hwc.removePushNotificationListener( pushListener );
1277        *
1278        * @example
1279        * // pushListenerManager is an object that will contain the listener callback as well as a variable
1280        * // referenced from the callback.
1281        * var pushListenerManager = {};
1282        * // doSomething is a function that is called from inside the callback.
1283        * pushListenerManager.doSomething = function( notifications )
1284        * {
1285        *    alert( "push notification:\n" + JSON.stringify(notifications) );
1286        *    return hwc.NOTIFICATION_CONTINUE;
1287        * }
1288        * // This is the callback function.
1289        * pushListenerManager.listener = function( notifications )
1290        * {
1291        *    return this.doSomething( notifications );
1292        * }
1293        * // Since the callback function references variables in its containing object, the containing object
1294        * // must be passed to hwc.addPushNotificationListener as well.
1295        * hwc.addPushNotificationListener( pushListenerManager.listener, pushListenerManager );
1296        * // when we want to remove the push listener, we call the following line:
1297        * hwc.removePushNotificationListener( pushListener, pushListenerManager );
1298        */
1299        hwc.removePushNotificationListener = function(PushNotificationListener, containingObject)
1300        {
1301            var i;
1302    	    hwc.traceEnteringMethod("hwc.removePushNotificationListener");
1303    		try {
1304    			if (hwc._pushnotificationlisteners.length === 0) {
1305    				return;
1306    			}
1307    
1308    			for (i = 0; i < hwc._pushnotificationlisteners.length; i++)
1309    			{
1310    				if (hwc._pushnotificationlisteners[i] === PushNotificationListener &&
1311    				hwc._pushnotificationlistenerContainingObjects[i] === containingObject)
1312    				{
1313    					hwc._pushnotificationlisteners.splice(i, 1);
1314    					hwc._pushnotificationlistenerContainingObjects.splice(i, 1);
1315    					if (hwc._pushnotificationlisteners.length === 0)
1316    					{
1317    						hwc.getDataFromContainer("stoppushnotificationlistener");
1318    					}
1319    					return;
1320    				}
1321    			}
1322    		} finally {
1323    			hwc.traceLeavingMethod("hwc.removePushNotificationListener");
1324    		}
1325        };
1326    
1327        /** 
1328         * A constant indicating that other push notification listeners should continue to be called.
1329         * Used as a return value for {@link anonymous.PushNotificationListener} functions.
1330         * @type number
1331         */
1332        hwc.NOTIFICATION_CONTINUE = 0;
1333        /**
1334         * A constant indicating that no more push notification listeners should be called.
1335         * Used as a return value for {@link anonymous.PushNotificationListener} functions.
1336         * @type number
1337         */
1338        hwc.NOTIFICATION_CANCEL = 1;
1339    
1340        /**
1341         * A sample implementation of a {@link anonymous.PushNotificationListener} callback function.
1342         *
1343         * @param {Array} notifications Array of notifications.
1344         */
1345        hwc.sample_PushNotificationListener = function(notifications)
1346        {
1347            return hwc.NOTIFICATION_CONTINUE;
1348        };
1349    
1350    
1351       /**
1352        * This object represents a hybrid app.
1353        * @classdesc
1354        * @public
1355        * @memberOf hwc
1356        * @param {number} moduleId The module id of this hybrid app.
1357        * @param {number} version The version of this hybrid app.
1358        * @param {string} displayName The display name of this hybrid app.
1359        * @param {number} iconIndex The index specifying the icon representing this Hybrid App.
1360        * @param {hwc.CustomIcon} defaultCustomIcon The default custom icon for this hybrid app.
1361        * @param {hwc.CustomIcon[]} customIconList An array of custom icon objects.
1362        */
1363       hwc.HybridApp = function (moduleId, version, displayName, iconIndex, defaultCustomIcon, customIconList)
1364       {
1365          this.ModuleID = moduleId;
1366          this.Version = version;
1367          this.DisplayName = displayName;
1368          this.IconIndex = iconIndex;
1369          this.defIcon = defaultCustomIcon;
1370          this.IconList = customIconList;
1371    
1372          /**
1373          * Gets the module ID for this hybrid app.
1374          * @public
1375          * @memberOf hwc.HybridApp
1376          * @returns {number} The module ID.
1377          */
1378          this.getModuleID = function ()
1379          {
1380             return this.ModuleID;
1381          };
1382    
1383          /**
1384          * Gets the version number for this hybrid app.
1385          * @public
1386          * @memberOf hwc.HybridApp
1387          * @returns {number} The version.
1388          */
1389          this.getVersion = function ()
1390          {
1391             return this.Version;
1392          };
1393    
1394          /**
1395          * Gets the display name for this hybrid app.
1396          * @public
1397          * @memberOf hwc.HybridApp
1398          * @returns {string} The display name.
1399          */
1400          this.getDisplayName = function ()
1401          {
1402             return this.DisplayName;
1403          };
1404    
1405          /**
1406          * Gets the icon index used in the list of built-in icons.
1407          * @public
1408          * @memberOf hwc.HybridApp
1409          * @returns {number} The icon index
1410          */
1411          this.getIconIndex = function ()
1412          {
1413             return this.IconIndex;
1414          };
1415    
1416          /**
1417          * Gets the default custom icon object of this hybrid app.
1418          * @public
1419          * @memberOf hwc.HybridApp
1420          * @returns {hwc.CustomIcon} The default custom icon of this hybrid app.  Null if this hybrid app does not have a custom icon.
1421          */
1422          this.getDefaultCustomIcon = function ()
1423          {
1424             return this.defIcon;
1425          };
1426    
1427          /**
1428          * Gets the list of custom icons associated with this hybrid app.
1429          * @public
1430          * @memberOf hwc.HybridApp
1431          * @returns {hwc.CustomIcon[]} The array of custom icon objects.  Null if this hybrid app has no custom icons.
1432          */
1433          this.getCustomIconList = function ()
1434          {
1435             return this.IconList;
1436          };
1437    
1438          /**
1439          * Return a {@link hwc.ClientVariables} object for the given module id and version.
1440          * @public
1441          * @memberOf hwc.HybridApp
1442          * @returns {hwc.ClientVariables} The {@link hwc.ClientVariables} object for this hybrid app.
1443          */
1444          this.getClientVariables = function()
1445          {
1446            return hwc.getClientVariables( this.ModuleID, this.Version );
1447          };
1448       };
1449    
1450       /**
1451        * An array of {@link anonymous.ApplicationListener} callback functions.
1452        * @private
1453        * @type {anonymous.ApplicationListener[]}
1454        */
1455       hwc._applicationListeners = [];
1456       /**
1457        * An array of objects containing {@link anonymous.ApplicationListener} callback functions.
1458        * The containing objects need to be kept track of in the case that a callback function references
1459        * a variable from its containing object.
1460        * @private
1461        * @type {Array}
1462        */
1463       hwc._applicationListenerContainingObjects = [];
1464    
1465       /**
1466        * This is the main entry of application notification. The native code should be
1467        * hardcoded to call this function internally.
1468        * @private
1469        */
1470       hwc._applicationListenerNotification = function (event, moduleId, version)
1471       {
1472          var i, containingObject;
1473    	  hwc.traceEnteringMethod("hwc._applicationListenerNotification");
1474          
1475    	  try {
1476    		  if (hwc._applicationListeners.length === 0){
1477    			 return;
1478    		  }
1479    
1480    		  for (i = 0; i < hwc._applicationListeners.length; i++)
1481    		  {
1482    			 containingObject = hwc._applicationListenerContainingObjects[i];
1483    			 if (containingObject !== null && containingObject !== undefined)
1484    			 {
1485    				hwc._applicationListeners[i].call(containingObject, event, moduleId, version);
1486    			 }
1487    			 else
1488    			 {
1489    				hwc._applicationListeners[i](event, moduleId, version);
1490    			 }
1491    		  }
1492    		  
1493    	  } finally {
1494    		  hwc.traceLeavingMethod("hwc._applicationListenerNotification");
1495    	  }
1496       };
1497    
1498       /**
1499        * Register the application listener.
1500        *
1501        * @param {anonymous.ApplicationListener} ApplicationListener The callback function for application changes.
1502        * @param {Object} [containingObject] The containing object of the listener method.  This parameter is only
1503        * required if the ApplicationListener references the containing object.
1504        * @public
1505        * @memberOf hwc
1506        * @example
1507        * // This is the callback function that will be passed to hwc.addAppListener.
1508        * var appListener = function( event, moduleId, version )
1509        * {
1510        *    if( event == hwc.APP_ADDED )
1511        *    {
1512        *       alert("A hybrid app has been added.");
1513        *    }
1514        * }
1515        * hwc.addAppListener( appListener );
1516        *
1517        * @example
1518        * // appListenerManager is an object that will contain the callback function as well as variables
1519        * // the callback function references.
1520        * var appListenerManager = {};
1521        * // doSomething is a function that is called from inside the callback function.
1522        * appListenerManager.doSomething = function( event )
1523        * {
1524        *    if( event == hwc.APP_REMOVED )
1525        *    {
1526        *       alert("A hybrid app has been removed.");
1527        *    }
1528        * }
1529        * // This is the callback function that will be passed to hwc.addAppListener.  It calls doSomething,
1530        * // the definition of which is in the containing function.
1531        * appListenerManager.listener = function( event, moduleId, version )
1532        * {
1533        *    this.doSomething( event );
1534        * }
1535        * // Since the listener callback function references a variable from its containing object,
1536        * // the containing object must be passed to hwc.addAppListener.
1537        * hwc.addAppListener( appListenerManager.listener, appListenerManager );
1538        */
1539       hwc.addAppListener = function (ApplicationListener, containingObject)
1540       {
1541    	  hwc.traceEnteringMethod("hwc.addAppListener");
1542    	  try {
1543    		  hwc._applicationListeners.push(ApplicationListener);
1544    		  hwc._applicationListenerContainingObjects.push(containingObject);
1545    		  // The native side will start to notify the notification when the first
1546    		  // listener is added
1547    		  if (hwc._applicationListeners.length === 1)
1548    		  {
1549    			 hwc.getDataFromContainer("startapplistener");
1550    		  }
1551    	 } finally {
1552    		  hwc.traceLeavingMethod("hwc.addAppListener");
1553    	 }
1554       };
1555    
1556       /**
1557        * Remove the application listener.  This function should be called with identical parameters
1558        * that were used to add the application listener with {@link hwc.addAppListener}.
1559        *
1560        * @public
1561        * @memberOf hwc
1562        * @param {anonymous.ApplicationListener} ApplicationListener The callback for application changes.
1563        * @param {Object} [containingObject] The containing object of the application listener function.
1564        * @example
1565        * // This is the callback function that will be passed to hwc.addAppListener.
1566        * var appListener = function( event, moduleId, version )
1567        * {
1568        *    if( event == hwc.APP_ADDED )
1569        *    {
1570        *       alert("A hybrid app has been added.");
1571        *    }
1572        * }
1573        * hwc.addAppListener( appListener );
1574        * // At some other point, if we want to remove the listener we use the following line of code:
1575        * hwc.removeAppListener( appListener );
1576        *
1577        * @example
1578        * // appListenerManager is an object that will contain the callback function as well as variables
1579        * // the callback function references.
1580        * var appListenerManager = {};
1581        * // doSomething is a function that is called from inside the callback function.
1582        * appListenerManager.doSomething = function( event )
1583        * {
1584        *    if( event == hwc.APP_REMOVED )
1585        *    {
1586        *       alert("A hybrid app has been removed.");
1587        *    }
1588        * }
1589        * // This is the callback function that will be passed to hwc.addAppListener.  It calls doSomething,
1590        * // the definition of which is in the containing function.
1591        * appListenerManager.listener = function( event, moduleId, version )
1592        * {
1593        *    this.doSomething( event );
1594        * }
1595        * // Since the listener callback function references a variable from its containing object,
1596        * // the containing object must be passed to hwc.addAppListener.
1597        * hwc.addAppListener( appListenerManager.listener, appListenerManager );
1598        * // At some other point, if we want to remove the listener we use the following line of code:
1599        * hwc.removeAppListener( appListenerManager.listener, appListenerManager );
1600        */
1601       hwc.removeAppListener = function (ApplicationListener, containingObject)
1602       {
1603          var i;
1604    	  hwc.traceEnteringMethod("hwc.removeAppListener");
1605    	  try {
1606    		  if (hwc._applicationListeners.length === 0) {
1607    			 return;
1608    		  }
1609    
1610    		  for (i = 0; i < hwc._applicationListeners.length; i++)
1611    		  {
1612    			 if (hwc._applicationListeners[i] === ApplicationListener &&
1613    				hwc._applicationListenerContainingObjects[i] === containingObject)
1614    			 {
1615    				hwc._applicationListeners.splice(i, 1);
1616    				hwc._applicationListenerContainingObjects.splice(i, 1);
1617    				if (hwc._applicationListeners.length === 0)
1618    				{
1619    				   hwc.getDataFromContainer("stopapplistener");
1620    				}
1621    				return;
1622    			 }
1623    		  }
1624    	  } finally {
1625    		  hwc.traceLeavingMethod("hwc.removeAppListener");
1626    	  }
1627       };
1628    
1629       /**
1630        * A constant indicating that the application list requires a refresh.
1631        * Used in {@link anonymous.ApplicationListener} callback functions as a possible value for event.
1632        * @type number
1633        */
1634       hwc.APP_REFRESH = 1;
1635       /**
1636        * A constant indicating that a hybrid app has been added.
1637        * Used in {@link anonymous.ApplicationListener} callback functions as a possible value for event.
1638        * @type number
1639        */
1640       hwc.APP_ADDED = 2;
1641       /**
1642        * A constant indicating that a hybrid app was updated.
1643        * Used in {@link anonymous.ApplicationListener} callback functions as a possible value for event.
1644        * @type number
1645        */
1646       hwc.APP_UPDATED = 3;
1647       /**
1648        * A constant indicating that a hybrid app was removed.
1649        * Used in {@link anonymous.ApplicationListener} callback functions as a possible value for event.
1650        * @type number
1651        */
1652       hwc.APP_REMOVED = 4;
1653    
1654       /**
1655        * A sample {@link anonymous.ApplicationListener} callback function.
1656        *
1657        * @param {number} event A number indicating what event has taken place (will be one of {@link hwc.APP_REFRESH},
1658        * {@link hwc.APP_ADDED}, {@link hwc.APP_UPDATED}, {@link hwc.APP_REMOVED}).
1659        * @param {number} moduleId The module id of the hyrbid app the event is about.
1660        * @param {number} version module The version of the hybrid app the event is about.
1661        */
1662       hwc.sample_AppListener = function (event, moduleId, version) {
1663       };
1664    
1665       /**
1666        * Gets the hybrid app that is currently open.
1667        *
1668        * @public
1669        * @memberOf hwc
1670        * @returns {hwc.HybridApp} The hybrid app that is currently open.
1671        * @example
1672        * var openHybridApp = hwc.getCurrentApp();
1673        */
1674       hwc.getCurrentApp = function()
1675       {
1676          var response, currentApp, app ;
1677          
1678    	  hwc.traceEnteringMethod("hwc.getCurrentApp");
1679          response = "";
1680    
1681          try {
1682             response = hwc.getDataFromContainer("getcurrentapp");
1683    
1684             if (response !== "")
1685             {
1686                app = JSON.parse(response);
1687                currentApp = new hwc.HybridApp(app.moduleId, app.version, app.displayName, app.iconIndex,
1688                                           hwc.createCustomIconObject(app.defaultCustomIcon, app.moduleId, app.version, hwc.DEFAULT_CUSTOM_ICON_INDEX),
1689                                           hwc.createCustomIconList(app.customIconList, app.moduleId, app.version));
1690             }
1691          } catch (ex){
1692            hwc.log("getCurrentApp error:" + ex.message, "ERROR", false);
1693          } finally {
1694    		  hwc.traceLeavingMethod("hwc.getCurrentApp");
1695    	  }
1696    
1697          return currentApp;
1698       };
1699    
1700       /**
1701        * Returns an array of {@link hwc.HybridApp} objects.
1702        *
1703        * @public
1704        * @memberOf hwc
1705        * @param {boolean} [completeList] If this parameter is set to true, then all apps that are user invocable or require
1706        *        activation will be returned.  If set to false or if it is not set, then if there is a default hybrid app
1707        *        only the default hybrid app will be returned (and if there is no default hybrid app it will return all hybrid apps
1708        *        that are user invocable or require activation).
1709        *        
1710        * @returns {hwc.HybridApp[]} An array of hybrid app objects.
1711        * @example
1712        * var apps = hwc.getInstalledApps();
1713        *
1714        * @example
1715        * var apps = hwc.getInstalledApps( true );
1716        */
1717       hwc.getInstalledApps = function( completeList )
1718       {
1719          var formattedCompleteList, response, installedApps, app, apps, i;
1720          
1721    	  hwc.traceEnteringMethod("hwc.getInstalledApps");
1722          formattedCompleteList = false;
1723          response = "";
1724          installedApps = [];
1725          
1726          if( completeList )
1727          {
1728             formattedCompleteList = true;
1729          }
1730          
1731    
1732          try {
1733             response = hwc.getDataFromContainer("getinstalledapps", "&getcompletelist=" + formattedCompleteList);
1734    
1735             if (response !== null && response !== undefined && response !== "")
1736             {
1737                apps = JSON.parse(response);
1738                for (i=0; i<apps.length; i++) {
1739                   app = apps[i];
1740                   installedApps[i] = new hwc.HybridApp(app.moduleId, app.version, app.displayName, app.iconIndex,
1741                                        hwc.createCustomIconObject(app.defaultCustomIcon, app.moduleId, app.version, hwc.DEFAULT_CUSTOM_ICON_INDEX),
1742                                        hwc.createCustomIconList(app.customIconList, app.moduleId, app.version));
1743                }
1744             }
1745          } catch (ex){
1746            hwc.log("getInstalledApps error:" + ex.message, "ERROR", false);
1747          } finally {
1748    		  hwc.traceLeavingMethod("hwc.getInstalledApps");
1749    	  }
1750    
1751          return installedApps;
1752       };
1753    
1754       /**
1755        * Returns an array of {@link hwc.HybridApp} objects that are server initiated.
1756        *
1757        * @public
1758        * @memberOf hwc
1759        * @returns {hwc.HybridApp[]} An array of server initiated hybrid apps.
1760        * @example
1761        * var serverInitiatedApps = hwc.getServerInitiatedApps();
1762        */
1763       hwc.getServerInitiatedApps = function()
1764       {
1765          var response = "", serverInitiatedApps = [], app, apps, i;
1766    
1767    	  hwc.traceEnteringMethod("hwc.getServerInitiatedApps");
1768          try {
1769             response = hwc.getDataFromContainer("getserverinitiatedapps");
1770    
1771             if (response !== null && response !== undefined && response !== "")
1772             {
1773                apps = JSON.parse(response);
1774                for (i=0; i<apps.length; i++) {
1775                   app = apps[i];
1776                   serverInitiatedApps[i] = new hwc.HybridApp(app.moduleId, app.version, app.displayName, app.iconIndex,
1777                                        hwc.createCustomIconObject(app.defaultCustomIcon, app.moduleId, app.version, hwc.DEFAULT_CUSTOM_ICON_INDEX),
1778                                        hwc.createCustomIconList(app.customIconList, app.moduleId, app.version));
1779                }
1780             }
1781          } catch (ex){
1782            hwc.log("getServerInitiatedApps error:" + ex.message, "ERROR", false);
1783          } finally {
1784    		  hwc.traceLeavingMethod("hwc.getServerInitiatedApps");
1785    	  }
1786    
1787          return serverInitiatedApps;
1788       };
1789    
1790       /**
1791        * Gets a {@link hwc.HybridApp} object with the given module id and version.
1792        *
1793        * @public
1794        * @memberOf hwc
1795        * @param {number} moduleID The module ID of the hybrid app.
1796        * @param {number} version The version of the hybrid app.
1797        *
1798        * @returns {hwc.HybridApp} The hybrid app object, or null if there is no hybrid app with the given ID and version.
1799        *
1800        * @example
1801        * // Messages do not have a direct link to the hybrid app they belong to.  Instead they have
1802        * // the module ID and version of the hybrid app they belong to.  If you have a message and
1803        * // need to access its hybrid app, first you must call hwc.getAppByID.
1804        * var messages = hwc.getAllMessages();
1805        * if( messages.length > 0 )
1806        * {
1807        *   var app = hwc.getAppByID( messages[0].getModuleId(), messages[0].getModuleVersion() );
1808        * }
1809        */
1810       hwc.getAppByID = function (moduleID, version)
1811       {
1812          var response, appInstance, app, params;
1813          
1814    	  hwc.traceEnteringMethod("hwc.getAppByID");
1815          response = "";
1816          params = "&moduleid=" + moduleID + "&moduleversion=" + version;
1817    
1818          try {
1819             response = hwc.getDataFromContainer("getappbyid", params);
1820    
1821             if (response !== "")
1822             {
1823                app = JSON.parse(response);
1824                appInstance = new hwc.HybridApp(app.moduleId, app.version, app.displayName, app.iconIndex,
1825                                           hwc.createCustomIconObject(app.defaultCustomIcon, app.moduleId, app.version, hwc.DEFAULT_CUSTOM_ICON_INDEX),
1826                                           hwc.createCustomIconList(app.customIconList, app.moduleId, app.version));
1827             }
1828          } catch (ex){
1829            hwc.log("getAppByID error:" + ex.message, "ERROR", false);
1830          } finally {
1831    		hwc.traceLeavingMethod("hwc.getAppByID");
1832    	  }
1833    
1834          return appInstance;
1835       };
1836    
1837       /**
1838        * A constant indicating that {@link hwc.openApp} completed successfully.
1839        * This is a possible return value for {@link hwc.openApp}.
1840        * @type number
1841        */
1842       hwc.OPEN_APP_SUCCESS = 0;
1843       /**
1844        * A constant indicating that {@link hwc.openApp} failed because the specified app does not exist.
1845        * This is a possible return value for {@link hwc.openApp}.
1846        * @type number
1847        */
1848       hwc.OPEN_APP_NOT_EXIST = 1;
1849       /**
1850        * A constant indicating that {@link hwc.openApp} failed for an unspecified reason.
1851        * This is a possible return value for {@link hwc.openApp}.
1852        * @type number
1853        */
1854       hwc.OPEN_APP_OTHER = 2;
1855    
1856       /**
1857        * Launch the hybrid app with the given module ID and version.  The hybrid app will be opened on top of the hybrid app
1858        * that is open when hwc.openApp is called.  When the hybrid app that was opened with hwc.openApp exits, it will exit
1859        * to the hybrid app that was open when hwc.openApp was called.  It is possible to nest open hybrid apps, but it is
1860        * best not to have too many nested hybrid apps (eg: recursively opening hybrid apps) because each open hybrid app
1861        * takes up device memory.
1862        * 
1863        * @param {number} moduleId Module id of the hybrid app.
1864        * @param {number} version Version of the hybrid app.
1865        *
1866        * @returns {number} A constant indicating the result of opening the hybrid app (will be one of {@link hwc.OPEN_APP_SUCCESS},
1867        * {@link hwc.OPEN_APP_NOT_EXIST}, {@link hwc.OPEN_APP_OTHER}).
1868        * @public
1869        * @memberOf hwc
1870        *
1871        * @example
1872        * var apps = hwc.getInstalledApps();
1873        * if( apps.length > 0 )
1874        * {
1875        *    // Check to make sure the first app is not this app (the app that is currently running),
1876        *    // since we don't want to recursively open this app until memory runs out.
1877        *    if( hwc.getCurrentHybridApp.getDisplayName() != apps[0].getDisplayName() )
1878        *    {
1879        *       hwc.openApp( apps[0].getModuleID(), apps[0].getVersion() );
1880        *    }
1881        * }
1882        */
1883       hwc.openApp = function (moduleId, version)
1884       {
1885          var response;
1886    	  hwc.traceEnteringMethod("hwc.openApp");
1887          try {
1888              response = hwc.getDataFromContainer("openhybridapp", "&moduleid=" + moduleId + "&moduleversion=" + version);
1889    		  return parseInt(response, 10);
1890          } catch (ex){
1891            hwc.log("app.open error:" + ex.message, "ERROR", false);
1892          } finally {
1893    		hwc.traceLeavingMethod("hwc.openApp");
1894    	  }
1895       };
1896    
1897       /**
1898        * A constant indicating the custom icon index.
1899        * @type number
1900        */
1901       hwc.DEFAULT_CUSTOM_ICON_INDEX = -1;
1902    
1903       /**
1904       * Gets the Hybrid Web Container application connection ID.
1905       *
1906       * @public
1907       * @memberOf hwc
1908       * @returns {string} Application connection ID
1909       * @example
1910       * var appConnectionID = hwc.getApplicationConnectionID();
1911       */
1912       hwc.getApplicationConnectionID = function() {
1913           var response = "";
1914    	   
1915    	   hwc.traceEnteringMethod("hwc.getApplicationConnectionID");
1916           try
1917           {
1918               response = hwc.getDataFromContainer("getconnectionid");
1919           }
1920           catch (ex) { 
1921            hwc.log("get connection id error:" + ex.message, "ERROR", false); 
1922           } finally {
1923    		   hwc.traceLeavingMethod("hwc.getApplicationConnectionID");
1924    	   }
1925    
1926           return String(response);
1927       };
1928    
1929       /**
1930        * Gets the client variables of the hybrid app with given module id and version.
1931        *
1932        * @public
1933        * @memberOf hwc
1934        * @param {number} moduleID The module ID of the hybrid app.
1935        * @param {number} version The version of the hybrid app.
1936        * 
1937        * @returns {hwc.ClientVariables} A {@link hwc.ClientVariables} object, or null if there are no
1938        * ClientVariables for the hybrid app with the given module id and version.
1939        * @example
1940        * var apps = hwc.getInstalledApps();
1941        * // Loop through the apps, showing the client variables for each one.
1942        * for( var i = 0; i < apps.length; i++ )
1943        * {
1944        *    var app = apps[i];
1945        *    // Get the client variables.
1946        *    var clientVariables = hwc.getClientVariables( app.getModuleID(), app.getVersion() );
1947        *    if( clientVariables.getCount() > 0 )
1948        *    {
1949        *       // Get all the names of the variables for this app.
1950        *       var keys = clientVariables.getAllVariableNames();
1951        *       // Loop through all the variable for this app.
1952        *       for( var index = 0; index < keys.length; index++ )
1953        *       {
1954        *          // Get a specific variable by name.
1955        *          var variable = clientVariables.getVariableValueByName( keys[index] );
1956        *          alert( "variable name: " + keys[index] + "\nvariable value: " + variable );
1957        *       }
1958        *    }
1959        * }
1960        */
1961       hwc.getClientVariables = function (moduleID, version)
1962       {
1963          var response, clientVariables, parsedResponse, params; 
1964          
1965    	  hwc.traceEnteringMethod("hwc.getClientVariables");
1966          response = "";
1967          clientVariables = null;
1968    
1969          params = "&moduleid=" + moduleID + "&moduleversion=" + version;
1970          try
1971          {
1972             response = hwc.getDataFromContainer("getclientvariables", params);
1973    
1974             if (response !== "")
1975             {
1976                parsedResponse = JSON.parse( response );
1977                clientVariables = new hwc.ClientVariables( parsedResponse.version, parsedResponse.items );
1978             }
1979          }
1980          catch (ex)
1981          {
1982            hwc.log("getClientVariables error:" + ex.message, "ERROR", false);
1983          } finally {
1984    		  hwc.traceLeavingMethod("hwc.getClientVariables");
1985    	  }
1986    
1987          return clientVariables;
1988       };
1989    
1990       /**
1991        * Represents a ClientVariables object.
1992        *
1993        * @classdesc
1994        *
1995        * @public
1996        * @param {number} clientVariablesVersion  The version of client variables.
1997        * @param {Object} clientVariableItems    The json object that contains key/value pairs of client variable items.
1998        * @memberOf hwc
1999        */
2000       hwc.ClientVariables = function ( clientVariablesVersion, clientVariablesItems )
2001       {
2002          this.version = clientVariablesVersion;
2003          this.items = clientVariablesItems;
2004    
2005          /**
2006          * Gets the version of the client variables.
2007          * @returns {number} The version of the client variables.
2008          * @public
2009          * @memberOf hwc.ClientVariables
2010          */
2011          this.getVersion = function ()
2012          {
2013             return this.version;
2014          };
2015    
2016          /**
2017          * Gets the number of variables this {@link hwc.ClientVariables} contains.
2018          * @public
2019          * @memberOf hwc.ClientVariables
2020          * @returns {number} The number of variables.
2021          */
2022          this.getCount = function ()
2023          {
2024             var keys = this.getAllVariableNames();
2025    
2026             return keys.length;
2027          };
2028    
2029          /**
2030          * Gets an array containing the names of all variables in this {@link hwc.ClientVariables}.
2031          *
2032          * @public
2033          * @memberOf hwc.ClientVariables
2034          * @returns {string[]} The array holding the names of all variables contained in this {@link hwc.ClientVariables}.
2035          */
2036          this.getAllVariableNames = function ()
2037          {
2038             var result, prop;
2039    		 hwc.traceEnteringMethod("hwc.ClientVariables.getAllVariableNames");
2040    		 try {
2041    			 result = [];
2042    
2043    			 if ( this.items !== undefined  && this.items !== null )
2044    			 {
2045    				 for ( prop in this.items )
2046    				{
2047    				   if ( this.items.hasOwnProperty( prop ) && typeof this.items[ prop ]  === 'string' )
2048    				   {
2049    					  result.push( prop );
2050    				   }
2051    			   }
2052    			 }
2053    			 result.sort();
2054    			 return result;
2055    		 } finally {
2056    			 hwc.traceLeavingMethod("hwc.ClientVariables.getAllVariableNames");
2057    		 }
2058          };
2059    
2060    
2061          /**
2062          * Check if this {@link hwc.ClientVariables} has a variable by the given name.
2063          *
2064          * @public
2065          * @memberOf hwc.ClientVariables
2066          * @param {string} variableName The name of variable to check for.
2067          * 
2068          * @returns {boolean} True if this {@link hwc.ClientVariables} has a variable by the given name, false otherwise.
2069          */
2070          this.containsName = function ( variableName )
2071          {
2072             if ( this.items === undefined || this.items === null || ( typeof this.items[ variableName ]  !== 'string' ) )
2073             {
2074                return false;
2075             }
2076    
2077             return true;
2078          };
2079    
2080          /**
2081          * Gets the value of the variable with the given name.  If this {@link hwc.ClientVariables} does not have a variable
2082          * by the given name, a {@link hwc.ClientVariablesException} will be thrown.
2083          *
2084          * @public
2085          * @memberOf hwc.ClientVariables
2086          * @param {string} variableName The name of the variable to get the value of.
2087          *
2088          * @returns {string} The value of the variable.
2089          *
2090          * @throws {hwc.ClientVariableException} This exception is thrown when there is no variable by the given name in this {@link hwc.ClientVariables}.
2091          */
2092          this.getVariableValueByName = function ( variableName )
2093          {
2094             if ( !this.containsName( variableName ) )
2095             {
2096                throw new hwc.ClientVariablesException( hwc.ClientVariables.ITEM_NOT_FOUND, "Unable to find variable name: " + variableName );
2097             }
2098    
2099             return this.items[ variableName ];
2100          };
2101       };
2102    
2103        /**
2104        * This exception is thrown when {@link hwc.ClientVariables#getVariableValueByName} is called with a variable name that does not exist. 
2105        * @public
2106        * @memberOf hwc
2107        * @param {number} errCode The error code (will be {@link hwc.ClientVariables.ITEM_NOT_FOUND}).
2108        * @param {string} errMsg A message describing the error.
2109        * @classdesc
2110        */
2111        hwc.ClientVariablesException = function(errCode, errMsg) {
2112            this.errCode = errCode;
2113            this.errMsg = errMsg;
2114        };
2115    
2116        /**
2117         * A constant indicating that a variable does not exist in a {@link hwc.ClientVariables} object.
2118         * @type number
2119         */
2120        hwc.ClientVariables.ITEM_NOT_FOUND = 1;
2121    
2122       /**
2123        * Represents a CustomIcon.  Used with the {@link hwc.HybridApp} object.
2124        * @classdesc
2125        * @public
2126        * @memberOf hwc
2127        * @param {number} width The width of this custom icon.
2128        * @param {number} height The height of this custom icon.
2129        * @param {string} type The image type of this custom icon.
2130        * @param {string} name The name of this custom icon.
2131        * @param {string} path The file path of the unprocessed icon.
2132        * @param {string} processedPath The file path of the processed icon.
2133        * @param {number} moduleId The module ID of the hybrid app this icon is for.
2134        * @param {number} moduleVersion The module version of the hybrid app this icon is for.
2135        * @param {number} index The index of this custom icon.
2136        */
2137       hwc.CustomIcon = function (width, height, type, name, path, processedPath, moduleId, moduleVersion, index)
2138       {
2139          this.w = width;
2140          this.h = height;
2141          this.t = type;
2142          this.n = name;
2143          this.p = path;
2144          this.pp = processedPath;
2145          this.mi = moduleId;
2146          this.mv = moduleVersion;
2147          this.index = index;
2148    
2149          /**
2150           * Gets the width of this custom icon.
2151           * @public
2152           * @memberOf hwc.CustomIcon
2153           * @returns {number} The width of this custom icon.
2154           */
2155          this.getWidth = function ()
2156          {
2157             return this.w;
2158          };
2159    
2160          /**
2161           * Gets the height of this custom icon.
2162           * @public
2163           * @memberOf hwc.CustomIcon
2164           * @returns {number} The height of this custom icon.
2165           */
2166          this.getHeight = function ()
2167          {
2168             return this.h;
2169          };
2170    
2171          /**
2172           * Gets the image type of this custom icon.
2173           * @public
2174           * @memberOf hwc.CustomIcon
2175           * @returns {string} The file type of the image.
2176           */
2177          this.getType = function ()
2178          {
2179             return this.t;
2180          };
2181    
2182          /**
2183           * Gets the name of this custom icon.
2184           * @public
2185           * @memberOf hwc.CustomIcon
2186           * @returns {string} The name of this custom icon.
2187           */
2188          this.getName = function ()
2189          {
2190             return this.n;
2191          };
2192    
2193          /**
2194           * Gets the file path of the unprocessed icon.
2195           * @public
2196           * @memberOf hwc.CustomIcon
2197           * @returns {string} The file path of the unprocessed icon.
2198           */
2199          this.getImagePath = function ()
2200          {
2201             return this.p;
2202          };
2203    
2204          /**
2205           * Gets the file path of the processed icon.
2206           * @public
2207           * @memberOf hwc.CustomIcon
2208           * @returns {string} The file path of the processed icon.
2209           */
2210          this.getProcessedImagePath = function ()
2211          {
2212             return this.pp;
2213          };
2214    
2215          /**
2216           * Gets the URL of this custom icon.  It is possible to call this function directly, but generally
2217           * it is easier simply to call {@link hwc.getAppIconUrl} or {@link hwc.getMsgIconUrl}.  Those
2218           * functions handle both cases where there is and isn't a custom icon for the hybrid app or message.
2219           *
2220           * @public
2221           * @memberOf hwc
2222           * @param {boolean} processed When set to true, the URL of the processed icon will be returned.
2223           * When set to false, the URL of the unprocessed icon will be returned.
2224           *
2225           * @returns {string} The URL to the target icon.
2226           * @example
2227           * var apps = hwc.getInstalledApps();
2228           * var app = apps[0];
2229           * // If app doesn't have a custom icon, then customIcon will be null.
2230           * var customIcon = app.getDefaultCustomIcon();
2231           * if( customIcon != null )
2232           * {
2233           *    // Create the image element.
2234           *    var image = document.createElement( "img" );
2235           *    // Set the source of the image to the icon URL.
2236           *    image.setAttribute( 'src', customIcon.getIconUrl() );
2237           *    // Add the image element to the page.
2238           *    document.body.appendChild( image );
2239           * }
2240           */
2241          this.getIconUrl = function (processed)
2242          {
2243              return hwc.getCustomIconUrl(this.mi, this.mv, this.index, processed);
2244          };
2245       };
2246    
2247       /**
2248        * This method is called internally.
2249        * @private	
2250        * @param {Object} jsonObj The JSON object containing information about the custom icon.
2251        * @param {number} moduleId The module ID of the hybrid app this custom icon belongs to.
2252        * @param {number} moduleVersion The module version of the hybrid app this custom icon belongs to.
2253        * @param {number} index The index of this custom icon.
2254        * @returns {hwc.CustomIcon} The new CustomIcon object.
2255        */
2256       hwc.createCustomIconObject = function(jsonObj, moduleId, moduleVersion, index)
2257       {
2258          if (jsonObj === null) {
2259             return null;
2260          }
2261    
2262          if (jsonObj === undefined) {
2263             return undefined;
2264          }
2265    
2266          return new hwc.CustomIcon(jsonObj.width, jsonObj.height, jsonObj.type, jsonObj.name, jsonObj.path, jsonObj.processedPath,
2267                moduleId, moduleVersion, index);
2268       };
2269    
2270       /**
2271        * This method is called internally
2272        * @private	
2273        * @param {Array} jsonArr An array of JSON objects that contain information about custom icons
2274        * @param {number} moduleId The module ID that will be associated with the custom icons
2275        * @param {number} moduleVersion The module version that will be associated with the custom icons
2276        * @returns {hwc.CustomIcon[]} An array of CustomIcon objects
2277        */
2278       hwc.createCustomIconList = function (jsonArr, moduleId, moduleVersion)
2279       {
2280          var iconArray, i, icon;
2281          iconArray = [];
2282          
2283          if (jsonArr === null) {
2284             return null;
2285          }
2286    
2287          if (jsonArr === undefined) { 
2288             return undefined;
2289          }
2290    
2291          if (jsonArr.length > 0)
2292          {
2293             for (i=0; i<jsonArr.length; i++)
2294             {
2295                icon = hwc.createCustomIconObject(jsonArr[i], moduleId, moduleVersion, i);
2296                if (icon !== null && icon !== undefined){
2297                   iconArray.push(icon);
2298                }
2299             }
2300          }
2301    
2302          return iconArray;
2303       };
2304    
2305    
2306       /**
2307        * Gets the URL to the custom icon.  This function is used by {@link hwc.CustomIcon#getIconUrl}.
2308        *
2309        * @public
2310        * @memberOf hwc
2311        * @param {number} moduleId The module Id of the hybrid app the custom icon belongs to.
2312        * @param {number} moduleVersion The version of the hybrid app the custom icon belongs to.
2313        * @param {number} iconIndex The index of the custom icon.
2314        * @param {boolean} processed Whether to get the processed icon (true), or the unprocessed icon (false).
2315        *
2316        * @returns {string} The URL to the target icon.
2317        */
2318       hwc.getCustomIconUrl = function (moduleId, moduleVersion, iconIndex, processed)
2319       {
2320          return getRequestUrl("customicon", "moduleid=" + moduleId+ "&moduleversion=" + moduleVersion + "&iconindex=" + iconIndex + "&processed=" + processed);
2321       };
2322    
2323       /**
2324        * Gets the icon URL for the built-in icon.  This function is used by {@link hwc.getMsgIconUrl} and {@link hwc.getAppIconUrl}.
2325        * It is possible to call this function directly, but generally it is easier simply to call {@link hwc.getAppIconUrl} or
2326        * {@link hwc.getMsgIconUrl} instead.  Those functions handle both cases where there is and isn't a custom icon for the hybrid app or message.
2327        *
2328        * @public
2329        * @memberOf hwc
2330        * @param {number} iconIndex The index of the built-in icon.
2331        * @param {boolean} processed Whether or not to get the URL of the processed icon (true) or the unprocessed icon (false).
2332        *
2333        * @returns {string} The URL to the icon.
2334        * @example
2335        * // Create the image element.
2336        * var builtInIcon = document.createElement( "img" );
2337        * // Set the source of the image to the icon URL.
2338        * builtInIcon.setAttribute( 'src', hwc.getBuiltInIconUrl(56, false) );
2339        * // Add the image element to the page.
2340        * document.body.appendChild( builtInIcon );
2341        */
2342       hwc.getBuiltInIconUrl = function (iconIndex, processed)
2343       {
2344           return getRequestUrl("clienticon", "iconindex=" + iconIndex + "&processed=" + processed);
2345       };
2346    
2347       /**
2348        * This function gets the URL of the icon for a message object depending on its
2349        * processed status and whether there are custom icons defined.
2350        *
2351        * @public
2352        * @memberOf hwc
2353        * @param {hwc.Message} msg The message object
2354        *
2355        * @returns {string} The url to access the icon.
2356        * @example
2357        * var messages = hwc.getAllMessages();
2358        * if( messages.length > 0 )
2359        * {
2360        *    // Create the image element.
2361        *    var messageIcon = document.createElement("img");
2362        *    // Set the source of the image to the icon URL.
2363        *    messageIcon.setAttribute( 'src', hwc.getMsgIconUrl( messages[0] ) );
2364        *    // Add the image element to the page.
2365        *    document.body.appendChild( messageIcon );
2366        * }
2367        */
2368       hwc.getMsgIconUrl = function (msg)
2369       {
2370    	  hwc.traceEnteringMethod("hwc.getMsgIconUrl");
2371    	  try {
2372    		  var app = hwc.getAppByID(msg.getModuleId(), msg.getModuleVersion());
2373    		  if (app === null || app === undefined) {
2374    			 return hwc.getBuiltInIconUrl(msg.getIconIndex(), msg.isProcessed());
2375    		  } else {
2376    			 return hwc.getAppIconUrl(app, msg.isProcessed());
2377    		  }
2378    	  } finally {
2379    		  hwc.traceLeavingMethod("hwc.getMsgIconUrl");
2380    	  }
2381       };
2382    
2383    
2384       /**
2385        * This function gets the URL of the icon for a hybrid app depending on whether custom icons are defined.
2386        *
2387        * @public
2388        * @memberOf hwc
2389        * @param {hwc.HybridApp} app The hybrid app for which the icon URL is desired.
2390        * @param {boolean} processed Whether to get the URL of the processed icon (true) or the URL of the unprocessed icon (false).
2391        *
2392        * @returns {string} The URL of the icon.
2393        * @example
2394        * var apps = hwc.getInstalledApps();
2395        * if( apps.length > 0 )
2396        * {
2397        *    var hybridApp = apps[0];
2398        *    // Create the image element.
2399        *    var hybridAppIcon = document.createElement("img");
2400        *    // Set the source of the image to the icon URL.
2401        *    hybridAppIcon.setAttribute( 'src', hwc.getAppIconUrl( hybridApp, false ) );
2402        *    // Add the image element to the page.
2403        *    document.body.appendChild( hybridAppIcon );
2404        * }
2405        */
2406       hwc.getAppIconUrl = function(app, processed)
2407       {
2408    	  hwc.traceEnteringMethod("hwc.getAppIconUrl");
2409    	  try {
2410    		  var ci = app.getDefaultCustomIcon();
2411    		  if (ci !== null && ci !== undefined)
2412    		  {
2413    			 return ci.getIconUrl(processed);
2414    		  }
2415    		  else
2416    		  {
2417    			 return hwc.getBuiltInIconUrl(app.getIconIndex(), processed);
2418    		  }
2419    	  } finally {
2420    		  hwc.traceLeavingMethod("hwc.getAppIconUrl");
2421    	  }
2422       };
2423    
2424       /**
2425        * Represents a message received by the HWC.
2426        *
2427        * @classdesc
2428        * @public
2429        * @memberOf hwc
2430        * @param {number} msgId The message ID of this message.
2431        * @param {Date} date The date this message was received.
2432        * @param {number} icon The icon index for this message.
2433        * @param {string} sender The sender of this message.
2434        * @param {boolean} isRead Whether this message has been read or not.
2435        * @param {boolean} processed Whether this message has been processed or not.
2436        * @param {number} priority The priority of this message (must be either {@link hwc.MSG_PRIORITY_HIGH} or {@link hwc.MSG_PRIORITY_NORMAL}).
2437        * @param {string} subject The subject of this message.
2438        * @param {number} module The module ID of the hybrid app associated with this message.
2439        * @param {number} version The version of the hybrid app associated with this message.
2440        */
2441       hwc.Message = function (msgId, date, icon, sender, isRead, processed, priority, subject, module, version)
2442       {
2443          this.msgId = msgId;
2444          this.recvDate = date;
2445          this.iconIndex = icon;
2446          this.subject = subject;
2447          this.moduleId = module;
2448          this.version = version;
2449          this.processed = processed;
2450          this.sender = sender;
2451          this.isread = isRead;
2452          this.priority = priority;
2453    
2454          /**
2455           * Gets the message ID of this message.
2456           * @public
2457           * @memberOf hwc.Message
2458           * @returns {number} The message ID of this message.\
2459           */
2460          this.getMessageId = function ()
2461          {
2462             return this.msgId;
2463          };
2464    
2465          /**
2466           * Gets the date this message was received.
2467           * @public
2468           * @memberOf hwc.Message
2469           * @returns {Date} The date this message was received.
2470           */
2471          this.getReceivedDate = function ()
2472          {
2473             return this.recvDate;
2474          };
2475    
2476          /**
2477           * Gets the icon index of this message.
2478           * @public
2479           * @memberOf hwc.Message
2480           * @returns {number} The icon index of this message.
2481           */
2482          this.getIconIndex = function ()
2483          {
2484             return this.iconIndex;
2485          };
2486    
2487          /**
2488           * Gets the sender of this message.
2489           * @public
2490           * @memberOf hwc.Message
2491           * @returns {string} The sender of this message.
2492           */
2493          this.getSender = function ()
2494          {
2495             return this.sender;
2496          };
2497    
2498          /**
2499           * Gets whether this message has been read or not.
2500           * @public
2501           * @memberOf hwc.Message
2502           * @returns {boolean} Whether this message has been read (true) or not (false).
2503           */
2504          this.isRead = function ()
2505          {
2506             return this.isread;
2507          };
2508    
2509          /**
2510           * Gets the subject of this message.
2511           * @public
2512           * @memberOf hwc.Message
2513           * @returns {string} The subject of this message.
2514           */
2515          this.getSubject = function ()
2516          {
2517             return this.subject;
2518          };
2519    
2520          /**
2521           * Gets the module ID of the hybrid app this message belongs to.
2522           * @public
2523           * @memberOf hwc.Message
2524           * @returns {number} The module ID of the hybrid app this message belongs to.
2525           */
2526          this.getModuleId = function ()
2527          {
2528             return this.moduleId;
2529          };
2530    
2531          /**
2532           * Gets the version of the hybrid app this message belongs to.
2533           * @public
2534           * @memberOf hwc.Message
2535           * @returns {number} The version of the hybrid app this message belongs to.
2536           */
2537          this.getModuleVersion = function ()
2538          {
2539             return this.version;
2540          };
2541    
2542          /**
2543           * Gets whether this message has been processed or not. A message is generally marked as processed once
2544           * the user submits changes from the hybrid app that was launched from the message.
2545           *
2546           * @public
2547           * @memberOf hwc.Message
2548           * @returns {boolean} True if this message has been processed, false otherwise.
2549           */
2550          this.isProcessed = function ()
2551          {
2552             return this.processed;
2553          };
2554    
2555          /**
2556           * Gets the priority of the message.
2557           *
2558           * @public
2559           * @memberOf hwc.Message
2560           * @returns {number} A constant indicating the priority of the message.
2561           * Will be either {@link hwc.MSG_PRIORITY_NORMAL} or {@link hwc.MSG_PRIORITY_HIGH}.
2562           */
2563          this.getPriority = function ()
2564          {
2565             if (this.priority === hwc.MSG_PRIORITY_HIGH) {
2566                return hwc.MSG_PRIORITY_HIGH;
2567             } else {
2568                return hwc.MSG_PRIORITY_NORMAL;
2569             }
2570          };
2571          
2572    
2573          /**
2574           * Updates the read status of the message.
2575           *
2576           * @public
2577           * @memberOf hwc.Message
2578           * @param {boolean} status The new read status.
2579           */
2580          this.updateRead = function(status)
2581          {
2582             hwc.updateMessageRead(this.msgId, status);
2583             this.isread = status;
2584          };
2585    
2586          /**
2587           * Updates the processed status of the message.
2588           * @public
2589           * @memberOf hwc.Message
2590           * @param {boolean} status The new processed status.
2591           */
2592          this.updateProcessed = function(status)
2593          {
2594             hwc.updateMessageProcessed(this.msgId, status);
2595             this.processed = status;
2596          };
2597       };
2598    
2599       /**
2600        * Represents a filter used to filter messages.
2601        * Pass in null for any parameter you do not wish to filter (or do not pass in such parameters at all).
2602        *
2603        * @classdesc
2604        * @public
2605        * @memberOf hwc
2606        * @param {string} [sender] The sender of the message.
2607        * @param {string} [subject] The subject of the message.
2608        * @param {number} [moduleId] The associated application module ID.
2609        * @param {number} [version] The associated application module verions.
2610        * @param {boolean} [isread] The read status.
2611        * @param {boolean} [processed] The processed status.
2612        *
2613        */
2614       hwc.MessageFilter = function (sender, subject, moduleId, version, isread, processed)
2615       {
2616          this.sender = sender;
2617          this.subject = subject;
2618          this.moduleId = moduleId;
2619          this.version = version;
2620          this.isRead = isread;
2621          this.processed = processed;
2622       };
2623    
2624       /**
2625        * An array of message listener callback functions.
2626        * @private
2627        * @type {anonymous.MessageListener[]}
2628        */
2629       hwc._messageListeners = [];
2630       /**
2631        * An array of objects containing message listener callback functions.
2632        * The containing objects need to be kept track of since the callback functions may reference
2633        * variables in the containing object.
2634        * @private
2635        * @type Array
2636        */
2637       hwc._messageListenerContainingObjects = [];
2638       /**
2639        * An array of {@link hwc.MessageFilter} objects.
2640        * @private
2641        * @type {hwc.MessageFilter[]}
2642        */
2643       hwc._messageListenerFilters = []; // Array of MessageFilter
2644    
2645       /**
2646        * This is the main entry of message notification. The native code should be
2647        * hardcoded to call this function
2648        * @private
2649        * @param {number} flag Will be one of: {@link hwc.MSG_ADDED}, {@link hwc.MSG_REMOVED}, {@link hwc.MSG_UPDATED}, {@link hwc.MSG_REFRESH}
2650        * @param {number} msgId The message id that this notification is about.
2651        */
2652       hwc._messageListenerNotification = function (flag, msgId)
2653       {
2654          var i, filter, msg, containingObject;
2655    	  hwc.traceEnteringMethod("hwc._messageListenerNotification");
2656    	  try {
2657    		  if (hwc._messageListeners.length === 0)
2658    		  {
2659    			 return;
2660    		  }
2661    
2662    		  msg = hwc.getMessageByID(msgId);
2663    		  for (i = 0; i < hwc._messageListeners.length; i++)
2664    		  {
2665    			 filter = hwc._messageListenerFilters[i];
2666    			 if (filter !== null && filter !== undefined)
2667    			 {
2668    				if( msg === null )
2669    				{
2670    				   // a null message should pass no filter
2671    					  continue;
2672    				}
2673    				if (filter.sender !== null && filter.sender !== undefined)
2674    				{
2675    				   if (msg.getSender().toLowerCase() !== filter.sender.toLowerCase()) {
2676    					  continue;
2677    				   }
2678    				}
2679    
2680    				if (filter.subject !== null && filter.subject !== undefined)
2681    				{
2682    				   if (msg.getSubject() !== filter.subject) {
2683    					  continue;
2684    				   }
2685    				}
2686    
2687    				if (filter.moduleId !== null && filter.moduleId !== undefined)
2688    				{
2689    				   if (msg.getModuleId() !== filter.ModuleId) {
2690    					  continue;
2691    				   }
2692    				}
2693    
2694    				if (filter.version !== null && filter.version !== undefined)
2695    				{
2696    				   if (msg.getVersion() !== filter.version) {
2697    					  continue;
2698    				   }
2699    				}
2700    
2701    				if (filter.isRead !== null && filter.isRead !== undefined)
2702    				{
2703    				   if (msg.getRead() !== filter.isRead) {
2704    					  continue;
2705    				   }
2706    				}
2707    
2708    				if (filter.processed !== null && filter.processed !== undefined)
2709    				{
2710    				   if (msg.getProcessed() !== filter.processed) {
2711    					  continue;
2712    				   }
2713    				}
2714    			 }
2715    
2716    			 containingObject = hwc._messageListenerContainingObjects[i];
2717    			 if (containingObject !== null && containingObject !== undefined)
2718    			 {
2719    				hwc._messageListeners[i].call(containingObject, flag, msgId);
2720    			 }
2721    			 else
2722    			 {
2723    				hwc._messageListeners[i](flag, msgId);
2724    			 }
2725    		  }
2726    	  } finally {
2727    		  hwc.traceLeavingMethod("hwc._messageListenerNotification");
2728    	  }
2729       };
2730    
2731       /**
2732        * Registers a message listener.
2733        *
2734        * @public
2735        * @memberOf hwc
2736        * @param {hwc.MessageFilter} filters The message filter that message events must pass to get passed to the {@link anonymous.MessageListener}.
2737        * If no filter is desired, then null can be used for this parameter.
2738        * @param {anonymous.MessageListener} MessageListener The callback function for message changes.
2739        * @param {Object} [containingObject] The containing object of the message listener.  If a message listener callback function
2740        * references variables in its containing object, then the containing object should be passed to this function.
2741        * @example
2742        * // soSomething is a global function called by the listener callback.
2743        * var doSomething = function()
2744        * {
2745        *    alert("New message!");
2746        * }
2747        * // messageListener is the callback function passed to hwc.addMessageListener.
2748        * var messageListener = function( flag, messageId )
2749        * {
2750        *    if( flag == hwc.MSG_ADDED )
2751        *    {
2752        *       doSomething();
2753        *    }
2754        * }
2755        * // We do not want to filter the message events the listener will get invoked for, so pass null for the first parameter.
2756        * hwc.addMessageListener( null, messageListener );
2757        *
2758        * @example
2759        * // someObject is an object that will contain the listener callback as well as a variable referenced by the callback.
2760        * var someObject = {};
2761        * // doSomething is a function referenced by the callback function.
2762        * someObject.doSomething = function()
2763        * {
2764        *    alert("New message!");
2765        * }
2766        * // messageListener is the callback that will be passed to hwc.addMessageListener.
2767        * someObject.messageListener = function( flag, messageId )
2768        * {
2769        *    if( flag == hwc.MSG_ADDED )
2770        *    {
2771        *       this.doSomething();
2772        *    }
2773        * }
2774        * // Create a filter so that not all message events will invoke our callback function.
2775        * // Only events about messages with a subject of "Subject" will trigger our callback function.
2776        * var filter = new hwc.MessageFilter( null, "Subject", null, null, null, null);
2777        * // The callback function references a variable in its containing object, so we need to pass in the containing object
2778        * // in addition to the filter and the callback function.
2779        * hwc.addMessageListener( filter, someObject.messageListener, someObject );
2780        */
2781       hwc.addMessageListener = function (filters, MessageListener, containingObject)
2782       {
2783    	  hwc.traceEnteringMethod("hwc.addMessageListener");
2784    	  try {
2785    		  hwc._messageListenerFilters.push(filters);
2786    		  hwc._messageListeners.push(MessageListener);
2787    		  hwc._messageListenerContainingObjects.push(containingObject);
2788    		  if (hwc._messageListeners.length === 1)
2789    		  {
2790    			 hwc.getDataFromContainer("startmsglistener");
2791    		  }
2792    	  } finally {
2793    		  hwc.traceLeavingMethod("hwc.addMessageListener");
2794    	  }
2795       };
2796    
2797       /**
2798        * Removes the message listener.  The two parameters passed in to this function should match exactly the corresponding
2799        * parameters passed into {@link hwc.addMessageListener} when the message listener was added.
2800        *
2801        * @public
2802        * @memberOf hwc
2803        * @param {anonymous.MessageListener} MessageListener The callback for message changes.
2804        * @param {Object} [containingObject] If the containing object was given to {@link hwc.addMessageListener} when the message
2805        * listener was added, then it also must be passed into this function.
2806        * @example
2807        * // soSomething is a global function called by the listener callback.
2808        * var doSomething = function()
2809        * {
2810        *    alert("New message!");
2811        * }
2812        * // messageListener is the callback function passed to hwc.addMessageListener.
2813        * var messageListener = function( flag, messageId )
2814        * {
2815        *    if( flag == hwc.MSG_ADDED )
2816        *    {
2817        *       doSomething();
2818        *    }
2819        * }
2820        * // We do not want to filter the message events the listener will get invoked for, so pass null for the first parameter.
2821        * hwc.addMessageListener( null, messageListener );
2822        * // If we want to remove the listener at some other point, use the following line of code:
2823        * hwc.removeMessageListener( messageListener );
2824        *
2825        * @example
2826        * // someObject is an object that will contain the listener callback as well as a variable referenced by the callback.
2827        * var someObject = {};
2828        * // doSomething is a function referenced by the callback function.
2829        * someObject.doSomething = function()
2830        * {
2831        *    alert("New message!");
2832        * }
2833        * // messageListener is the callback that will be passed to hwc.addMessageListener.
2834        * someObject.messageListener = function( flag, messageId )
2835        * {
2836        *    if( flag == hwc.MSG_ADDED )
2837        *    {
2838        *       this.doSomething();
2839        *    }
2840        * }
2841        * // Create a filter so that not all message events will invoke our callback function.
2842        * // Only events about messages with a subject of "SI<4>" will trigger our callback function.
2843        * var filter = new hwc.MessageFilter( null, "SI<4>", null, null, null, null);
2844        * // The callback function references a variable in its containing object, so we need to pass in the containing object
2845        * // in addition to the filter and the callback function.
2846        * hwc.addMessageListener( filter, someObject.messageListener, someObject );
2847        * // If we want to remove the listener at some other point, use the following line of code:
2848        * hwc.removeMessageListener( messageListener, someObject );
2849        */
2850       hwc.removeMessageListener = function (MessageListener, containingObject)
2851       {
2852          var i;
2853    	  hwc.traceEnteringMethod("hwc.removeMessageListener");
2854    	  try {
2855    		  if (hwc._messageListeners.length === 0) {
2856    			 return;
2857    		  }
2858    
2859    		  for (i = 0; i < hwc._messageListeners.length; i++)
2860    		  {
2861    			 if (hwc._messageListeners[i]+"" === MessageListener+"" &&
2862    				hwc._messageListenerContainingObjects[i] === containingObject)
2863    			 {
2864    				hwc._messageListeners.splice(i, 1);
2865    				hwc._messageListenerFilters.splice(i, 1);
2866    				hwc._messageListenerContainingObjects.splice(i, 1);
2867    				if (hwc._messageListeners.length === 0)
2868    				{
2869    				   hwc.getDataFromContainer("stopmsglistener");
2870    				}
2871    				return;
2872    			 }
2873    		  }
2874    	  } finally {	  
2875    		  hwc.traceLeavingMethod("hwc.removeMessageListener");
2876    	  }
2877       };
2878    
2879       /**
2880        * A constant indicating that a message needs to be refreshed.  Used in {@link anonymous.MessageListener} callback functions.
2881        * @type number
2882        */
2883       hwc.MSG_REFRESH = 1;
2884       /**
2885        * A constant indicating that a message has been added.  Used in {@link anonymous.MessageListener} callback functions.
2886        * @type number
2887        */
2888       hwc.MSG_ADDED = 2;
2889       /**
2890        * A constant indicating that a message has been updated.  Used in {@link anonymous.MessageListener} callback functions.
2891        * @type number
2892        */
2893       hwc.MSG_UPDATED = 3;
2894       /**
2895        * A constant indicating that a message has been removed.  Used in {@link anonymous.MessageListener} callback functions.
2896        * @type number
2897        */
2898       hwc.MSG_REMOVED = 4;
2899       /**
2900        * A constant indicating a message has normal priority.  Used in {@link hwc.Message}.
2901        * @type number
2902        */
2903       hwc.MSG_PRIORITY_NORMAL = 1;
2904       /**
2905        * A constant indicating a message has high priority.  Used in {@link hwc.Message}.
2906        * @type number
2907        */
2908       hwc.MSG_PRIORITY_HIGH = 3;
2909    
2910       /**
2911        * A sample {@link anonymous.MessageListener} callback function.
2912        *
2913        * @param {number} flag A number indicating which message event occured (will be one of MSG_* constants).
2914        * @param {number} msgId The message id of the affected message.
2915        */
2916       hwc.sample_MessageListener = function (flag, msgId) {
2917       };
2918    
2919       /**
2920        * Gets received messages based on a filter and the existance of a default hybrid app.
2921        *
2922        * @public
2923        * @memberOf hwc
2924        * @param {hwc.MessageFilter} [messageFilter] A filter that all returned messages will pass.
2925        * If you do not want to filter based on a certain atribute, use null for that attribute when creating the filter.
2926        * If you do not want to filter at all, pass in null for this parameter or do not pass in this parameter at all.
2927        * @param {boolean} [completeList] If this parameter is set to true, then all messages will be returned.
2928        * If this parameter is set to false or if it is not set, then if there is a default hybrid app only the messages belonging
2929        * to the default hybrid app will be returned (and if there is no default hybrid app all messages will be returned).
2930        *
2931        * @returns {hwc.Message[]} An array of {@link hwc.Message} objects - the received messages.
2932        * @example
2933        * // get all messages that have the subject "a subject".
2934        * var filter = new hwc.MessageFilter( null, "a subject", null, null, null, null );
2935        * var messages = hwc.getAllMessages(filter);
2936        *
2937        * @example
2938        * // Get all messages without filtering, but if there is a default hybrid app only return its messages.
2939        * var messages = hwc.getAllMessages();
2940        *
2941        * @example
2942        * // Get all messages (without filtering) for all hybrid apps, even if there is a default hybrid app.
2943        * var messages = hwc.getAllMessages( null, true );
2944        */
2945       hwc.getAllMessages = function (filters, completeList) {
2946          var filtersUrlString, messages, i, message, formattedCompleteList,response, messageInstances;
2947              
2948    	  hwc.traceEnteringMethod("hwc.getAllMessages");
2949          formattedCompleteList = false;
2950          response = "";
2951          messageInstances = [];
2952          
2953          if ( completeList )
2954          {
2955             formattedCompleteList = true;
2956          }
2957          
2958          try {
2959             // Create filter url argument
2960             filtersUrlString = "";
2961             if( filters )
2962             {
2963                if( filters.sender !== undefined && filters.sender !== null )
2964                {
2965                   filtersUrlString = filtersUrlString + "&filtermessagesender=" + encodeURIComponent(filters.sender);
2966                }
2967                if( filters.subject !== undefined && filters.subject !== null &&  filters.subject !== undefined)
2968                {
2969                   filtersUrlString = filtersUrlString + "&filtermessagesubject=" + encodeURIComponent(filters.subject);
2970                }
2971                if( filters.moduleId !== undefined && filters.moduleId !== null )
2972                {
2973                   filtersUrlString = filtersUrlString + "&filtermessagemoduleid=" + encodeURIComponent(filters.moduleId);
2974                }
2975                if( filters.version !== undefined && filters.version !== null )
2976                {
2977                   filtersUrlString = filtersUrlString + "&filtermessageversion=" + encodeURIComponent(filters.version);
2978                }
2979                if( filters.isRead !== undefined && filters.isRead !== null )
2980                {
2981                   filtersUrlString = filtersUrlString + "&filtermessageisread=" + encodeURIComponent(filters.isRead);
2982                }
2983                if( filters.processed !== undefined && filters.processed !== null )
2984                {
2985                   filtersUrlString = filtersUrlString + "&filtermessageisprocessed=" + encodeURIComponent(filters.processed);
2986                }
2987             }
2988    
2989             filtersUrlString += "&getcompletelist=" + formattedCompleteList;
2990    
2991             response = hwc.getDataFromContainer("getmessages", filtersUrlString);
2992    
2993             if (response !== null && response !== undefined && response !== "")
2994             {
2995                messages = JSON.parse(response);
2996                for (i=0; i<messages.length; i++){
2997                   message = messages[i];
2998                   messageInstances[i] = new hwc.Message(message.id, new Date(message.milliseconds), message.iconIndex, message.sender, message.isRead,
2999                      message.isProcessed, message.priority, message.subject, message.module, message.version);
3000                }
3001             }
3002    
3003          }catch (ex){
3004            hwc.log("messages.getAll error:" + ex.message, "ERROR", false);
3005          } finally {
3006    		  hwc.traceLeavingMethod("hwc.getAllMessages");
3007    	  }
3008    
3009          return messageInstances;
3010       };
3011    
3012       /**
3013        * Gets a {@link hwc.Message} object with the given message ID.
3014        *
3015        * @public
3016        * @memberOf hwc
3017        * @param {number} msgId The message ID of the message to get.
3018        *
3019        * @returns {hwc.Message} A message object, or null if no message with given ID.
3020        * @example
3021        * // A message listener is one place that would likely need to call hwc.getMessageByID.
3022        * var messageListener = function( flag, messageID )
3023        * {
3024        *    // Since the callback function only gets the messageID, not the message itself, if we want
3025        *    // more information about the message we must call hwc.getMessageByID.
3026        *    var message = hwc.getMessageByID( messageID );
3027        *    if( message.getSubject() == "a special subject" )
3028        *    {
3029        *       alert( "An event occured for a special message!" );
3030        *    }
3031        * }
3032        * hwc.addMessageListener( null, messageListener );
3033        */
3034       hwc.getMessageByID = function (msgId)
3035       {
3036          var response, messageInstance, message;
3037          
3038    	  hwc.traceEnteringMethod("hwc.getMessageByID");
3039          response = "";
3040          messageInstance = null;
3041    
3042          try {
3043             response = hwc.getDataFromContainer("getmessagebyid", "&msgid=" + msgId);
3044    
3045             if (response !== null && response !== undefined && response !== "")
3046             {
3047                message = JSON.parse(response);
3048                messageInstance = new hwc.Message(message.id, new Date(message.milliseconds), message.iconIndex, message.sender, message.isRead,
3049                      message.isProcessed, message.priority, message.subject, message.module, message.version);
3050             }
3051          }catch (ex){ 
3052            hwc.log("messages.getMessageByID error:" + ex.message, "ERROR", false);
3053          } finally {
3054    		  hwc.traceLeavingMethod("hwc.getMessageByID");
3055    	  }
3056    
3057          return messageInstance;
3058       };
3059    
3060       /**
3061        * Updates the message read status.
3062        *
3063        * @public
3064        * @memberOf hwc
3065        * @param {number} msgId The id of message to update the read status for.
3066        * @param {boolean} status Whether the message will be set to read (true) or unread (false).
3067        * @example
3068        * // set all messages as read
3069        * var messages = hwc.getAllMessages();
3070        * for( var index = 0; index < messages.length; index++ )
3071        * {
3072        *    hwc.updateMessageRead( messages[index].getMessageId(), true );
3073        * }
3074        */
3075       hwc.updateMessageRead = function (msgId, status)
3076       {    
3077          var updateParms;
3078     	  hwc.traceEnteringMethod("hwc.updateMessageRead");
3079         try {
3080             updateParms = "&msgid=" + msgId + "&msgfield=read" + "&status=" + status;
3081             hwc.getDataFromContainer("updatemessage", updateParms);
3082          } catch (ex){
3083            hwc.log("Message.updateMsgRead error:" + ex.message, "ERROR", false);
3084          } finally {
3085     	    hwc.traceLeavingMethod("hwc.updateMessageRead");
3086    	  }
3087       };
3088    
3089       /**
3090        * Updates the message processed status.
3091        *
3092        * @public
3093        * @memberOf hwc
3094        * @param {number} msgId The id of message to update the processed status for.
3095        * @param {boolean} status Whether the message will be set to processed (true) or unprocessed (false).
3096        * @example
3097        * // set all messages as processed
3098        * var messages = hwc.getAllMessages();
3099        * for( var index = 0; index < messages.length; index++ )
3100        * {
3101        *    hwc.updateMessageProcessed( messages[index].getMessageId(), true );
3102        * }
3103        */
3104       hwc.updateMessageProcessed = function (msgId, status)
3105       {
3106          var updateParms;
3107     	  hwc.traceEnteringMethod("hwc.updateMessageProcessed");
3108          try {
3109             updateParms = "&msgid=" + msgId + "&msgfield=processed" + "&status=" + status;
3110             hwc.getDataFromContainer("updatemessage", updateParms);
3111          } catch (ex){
3112            hwc.log("Message.updateMsgProcessed error:" + ex.message, "ERROR", false);
3113          } finally {
3114    		hwc.traceLeavingMethod("hwc.updateMessageProcessed");
3115    	  }
3116       };
3117    
3118       /**
3119        * Removes (deletes) a message.
3120        *
3121        * @public
3122        * @memberOf hwc
3123        * @param {number} msgId The id of the message to be removed.
3124        * @example
3125        * // remove all messages
3126        * var messages = hwc.getAllMessages();
3127        * for( var index = 0; index < messages.length; index++ )
3128        * {
3129        *    hwc.removeMessage( messages[index].getMessageId() );
3130        * }
3131        */
3132       hwc.removeMessage = function(msgId) {
3133     	  hwc.traceEnteringMethod("hwc.removeMessage");
3134          try {
3135             hwc.getDataFromContainer("removemessage", "&msgid=" + msgId);
3136          } catch (ex){hwc.log("messages.remove error:" + ex.message, "ERROR", false);}
3137     	  finally {hwc.traceLeavingMethod("hwc.removeMessage");}
3138       };
3139    
3140       /**
3141        * A constant indicating that a message was successfully opened.  This is a possible return value for {@link hwc.openMessage}.
3142        * @type number
3143        */
3144       hwc.OPEN_MSG_SUCCESS = 0;
3145       /**
3146        * A constant indicating that a message could not be opened because no message with the given ID exists.
3147        * This is a possible return value for {@link hwc.openMessage}.
3148        * @type number
3149        */
3150       hwc.OPEN_MSG_NOT_EXIST = 1;
3151       /**
3152        * A constant indicating that a message could not be opened because there was no associated hybrid app.
3153        * This is a possible return value for {@link hwc.openMessage}.
3154        * @type number
3155        */
3156       hwc.OPEN_MSG_APP_NOT_EXIST = 2;
3157       /**
3158        * A constant indicating that a message could not be opened due to an unspecified error.
3159        * This is a possible return value for {@link hwc.openMessage}.
3160        * @type number
3161        */
3162       hwc.OPEN_MSG_OTHER = 3;
3163    
3164       /**
3165        * Launch the server initiated hybrid app associated with a message.  The hybrid app will be opened on top of the hybrid app
3166        * that is open when hwc.openMessage is called.  When the hybrid app that was opened with hwc.openMessage exits, it will exit
3167        * to the hybrid app that was open when hwc.openMessage was called.  It is possible to nest open hybrid apps, but it is
3168        * best not to have too many nested hybrid apps (eg: recursively opening hybrid apps) because each open hybrid app
3169        * takes up device memory.
3170        *
3171        * @public
3172        * @memberOf hwc
3173        * @param {number} msgId The id of message to open.
3174        *
3175        * @returns {number} A number indicating the success or failure of opening the message (will be one of {@link hwc.OPEN_MSG_SUCCESS},
3176        * {@link hwc.OPEN_MSG_NOT_EXIST}, {@link hwc.OPEN_MSG_APP_NOT_EXIST}, {@link hwc.OPEN_MSG_OTHER}).
3177        * @example
3178        * // get all messages, then open the first one
3179        * var messages = hwc.getAllMessages();
3180        * if( messages.length > 0 )
3181        * {
3182        *    hwc.openMessage( messages[0].getMessageId() );
3183        * }
3184        */
3185       hwc.openMessage = function(msgId) {
3186          var response;
3187    	  
3188     	  hwc.traceEnteringMethod("hwc.openMessage");
3189          try {
3190             response = hwc.getDataFromContainer("openmessage", "&msgid=" + msgId);
3191             return parseInt(response, 10);
3192          } catch (ex){
3193            hwc.log("messages.open error:" + ex.message, "ERROR", false);
3194          } finally {
3195    		  hwc.traceLeavingMethod("hwc.openMessage");
3196    	  }
3197       };
3198    
3199       /**
3200        * This function takes care of handling the XML HTTP request to communicate with the HWC native code on the different platforms.
3201        *
3202        * @private
3203        * @memberOf hwc
3204        *
3205        * @param {string} queryType A string indicating the type of query being sent to the native code.
3206        * This parameter must match up with a constant defined in the native code of the HWC.
3207        * @param {string} urlParams A string of parameters for the query, in a format such that it can
3208        * be added directly to the url.
3209        *
3210        * @returns {string} The response text of the request.
3211        * @example
3212        * // This example is an excerpt from hwc.getInstalledApps.  There are many examples of how to use this function in this file.
3213        * response = hwc.getDataFromContainer("getinstalledapps", "&getcompletelist=true");
3214        * if (response != null && response != undefined && response != "")
3215        * {
3216        *    var apps = JSON.parse(response);
3217        *    for(var i=0; i<apps.length; i++) {
3218        *       var app = apps[i];
3219        *       installedApps[i] = new hwc.HybridApp(app.moduleId, app.version, app.displayName, app.iconIndex,
3220        *                            hwc.createCustomIconObject(app.defaultCustomIcon, app.moduleId, app.version, hwc.DEFAULT_CUSTOM_ICON_INDEX),
3221        *                            hwc.createCustomIconList(app.customIconList, app.moduleId, app.version));
3222        *    }
3223        * }
3224        */
3225       hwc.getDataFromContainer = function( queryType, urlParams)
3226       {
3227          var response, xmlhttp;
3228    	  hwc.traceEnteringMethod("hwc.getDataFromContainer");
3229          response = "";
3230    	 if (urlParams === null || urlParams === undefined) {
3231    		 urlParams = "";
3232    	 }
3233    	 
3234    	 try {
3235    		 if (hwc.isWindowsMobile()) {
3236    			xmlhttp = hwc.getXMLHTTPRequest();
3237    			xmlhttp.open("GET", "/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam + "&" + urlParams, false );
3238    			xmlhttp.send("");
3239    			 response = xmlhttp.responseText;
3240    		 }
3241    		 else if (hwc.isAndroid()) {
3242    			response = _HWC.getData("http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam + urlParams);
3243    		 }
3244    		 else if (hwc.isBlackBerry()) {
3245    			// CR661210 and NA3-2487
3246    			if (hwc.isClosed()) {
3247    				return;
3248    			}
3249    			
3250    			xmlhttp = hwc.getXMLHTTPRequest();
3251    			xmlhttp.open("POST", "http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam + urlParams, false);
3252    			xmlhttp.send();
3253    			response = xmlhttp.responseText;
3254    		 }
3255    		 else if (hwc.isIOS()) {
3256    			xmlhttp = hwc.getXMLHTTPRequest();
3257    			xmlhttp.open("GET", "http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam + urlParams, false);
3258    			try
3259    			{
3260    			   xmlhttp.send("");
3261    			}
3262    			catch (ex)
3263    			{
3264    			   if (ex.message.search(/XMLHttpRequest Exception 101/) === -1)
3265    			   {
3266    				  throw ex;
3267    			   }
3268    			}
3269    			response = xmlhttp.responseText;
3270    		 }
3271    		 return response;
3272    	  }
3273    	  catch (ex1)
3274    	  {
3275    		 hwc.log( "hwc.getDataFromContainer error: " + ex1.message, "ERROR", false);
3276    	  } finally {
3277    		 hwc.traceLeavingMethod("hwc.getDataFromContainer");
3278    	  }
3279       };
3280    
3281       /**
3282        * This function takes care of handling the XML HTTP request to communicate with the HWC native code on different platforms.
3283        *
3284        * @private
3285        * @memberOf hwc
3286        * @param {string} queryType Indicates the type of query being sent to the native code.
3287        * This parameter must match up with a constant defined in the native code of the HWC.
3288        * @param {string} data Data to be sent with the request.
3289        *
3290        * @returns {string} The response text of the request.
3291        */
3292       hwc.postDataToContainer = function( queryType, data)
3293       {
3294          var response, xmlhttp;
3295          response = "";
3296          try
3297          {
3298             
3299             if (hwc.isWindowsMobile()) {
3300                xmlhttp = hwc.getXMLHTTPRequest();
3301                xmlhttp.open("POST", "/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam, false);
3302                xmlhttp.send(data);
3303                response = xmlhttp.responseText;
3304             }
3305             else if (hwc.isAndroid()) {
3306                response = _HWC.postData("http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam, data);
3307             }
3308             else if (hwc.isBlackBerry()) {
3309                // CR661210 and NA3-2487
3310                if (hwc.isClosed()) {
3311                    return;
3312                }
3313                
3314                xmlhttp = hwc.getXMLHTTPRequest();
3315                xmlhttp.open("POST", "http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam, false);
3316                xmlhttp.send(data);
3317                response = xmlhttp.responseText;
3318             }
3319             else if (hwc.isIOS()) {
3320                xmlhttp = hwc.getXMLHTTPRequest();
3321                xmlhttp.open("POST", "http://localhost/sup.amp?querytype=" + queryType + "&" + hwc.versionURLParam, false);
3322                try
3323                {
3324                   xmlhttp.send(data);
3325                }
3326                catch (ex)
3327                {
3328                   if (ex.message.search(/XMLHttpRequest Exception 101/) === -1)
3329                   {
3330                      throw ex;
3331                   }
3332                }
3333                response = xmlhttp.responseText;
3334             }
3335             return response;
3336          }
3337          catch (ex1)
3338          {
3339             hwc.log( "hwc.postDataToContainer error: " + ex1.message, "ERROR", false);
3340          }
3341       };
3342    
3343       var partialRequestUrl = null;
3344    
3345        /**
3346         * Gets a URL that can be used to get resources from the HWC.
3347         *
3348         * @private
3349         * @memberOf hwc
3350         * @param {string} queryType The type of query
3351         * @param {string} urlParams Additional parameters to send with the request.  Must be formated such that it can be appended to the url
3352         * (eg: "firstParam=value1&secondParam=value2").
3353         *
3354         * @returns {string} A URL that can be used to access resources.
3355         */
3356       getRequestUrl = function ( queryType, urlParams )
3357       {
3358          // Lazy load to prevent platform identification errors
3359          if (!partialRequestUrl)
3360          {
3361             partialRequestUrl = hwc.isWindowsMobile() ? "/sup.amp?querytype=" :
3362                hwc.isAndroid() ?
3363                ( window.location.protocol + "//" + window.location.hostname + "/" + window.location.pathname.split( '/' )[1] + "/sup.amp/querytype=" ) :
3364                hwc.isBlackBerry() || hwc.isIOS() ? "http://localhost/sup.amp?querytype=" :
3365                "";
3366          }
3367    
3368          return partialRequestUrl + queryType + "&" + hwc.versionURLParam + (urlParams ? '&' : "") + urlParams;
3369       };
3370    
3371       /**
3372        * Represents a Media Cache.  This object gives the option to use the cache when accessing .
3373        *
3374        * @classdesc
3375        * @public
3376        * @memberOf hwc
3377        * @static
3378        */
3379       hwc.MediaCache = {};
3380    
3381       /**
3382        * hwc.MediaCache.Policy An object containing constants representing the different caching policies.
3383        * @memberOf hwc.MediaCache
3384        */
3385       hwc.MediaCache.Policy = {};
3386    
3387       /**
3388        * hwc.MediaCache.Policy.SERVER_FIRST Use server first policy: requests will only be served from the cache if the server is unavailable.
3389        * @type {string}
3390        * @memberOf hwc.MediaCache
3391        */
3392       hwc.MediaCache.Policy.SERVER_FIRST = "ServerFirst";
3393       /**
3394        * hwc.MediaCache.Policy.CACHE_FIRST Use cache first policy: requests will be served from the cache if possible.
3395        * @type {string}
3396        * @memberOf hwc.MediaCache
3397        */
3398       hwc.MediaCache.Policy.CACHE_FIRST = "CacheFirst";
3399    
3400       /**
3401        * Creates a media cache URL for the resource.  The cache first policy will be used if no policy is specified.
3402        *
3403        * @public
3404        * @memberOf hwc.MediaCache
3405        * @param {string} resourceUrl The URL to the resource
3406        * @param {hwc.MediaCache.Policy} [policy] The optional cache policy to use.
3407        * If set, it must be either {@link hwc.MediaCache.Policy.SERVER_FIRST} or {@link hwc.MediaCache.Policy.CACHE_FIRST}.
3408        * Default policy is cache first.
3409        *
3410        * @returns {string} The URL that can be used to access the resource with the specified caching policy.
3411        * @example
3412        * // This line creates a url that can be used to retrieve the picture from the cache if possible, and from the server otherwise.
3413        * var mediaCacheURL = hwc.MediaCache.getUrl( "http://yourserver.com/Pictures/pentagon.jpg", hwc.MediaCache.Policy.CACHE_FIRST );
3414        * // The following function adds a picture to the page. Since the mediaCacheURL variable is used for the url, the picure will be
3415        * // retrieved from the cache if possible.
3416        * var addPicFromMediaCache = function()
3417        * {
3418        *    // Create the image element.
3419        *    var image = document.createElement( "img" );
3420        *    // Set the source of the image to the media cache URL.
3421        *    image.setAttribute( 'src', mediaCacheURL );
3422        *    // Add the image element to the page.
3423        *    document.body.appendChild( image );
3424        * }
3425        *
3426        * @example
3427        * // This line creates a url that can be used to retrieve the picture from the server if it is available, or the cache otherwise.
3428        * var mediaCacheURL_serverFirst = hwc.MediaCache.getUrl( "http://yourserver.com/Pictures/pentagon.jpg", hwc.MediaCache.Policy.SERVER_FIRST );
3429        * // The following function adds a picture to the page.  Since the mediaCacheURL_serverFirst variable is used for the url, the picture will be gotten
3430        * // from the server if the server is available, and from the cache otherwise.
3431        * var addPicFromMediaCache_ServerFirst = function()
3432        * {
3433        *    // Create the image element.
3434        *    var image = document.createElement( "img" );
3435        *    // Set the source of the image to the media cache URL.
3436        *    image.setAttribute( 'src', mediaCacheURL_serverFirst );
3437        *    // Add the image element to the page.
3438        *    document.body.appendChild( image );
3439        * }
3440        *
3441        */
3442       hwc.MediaCache.getUrl = function ( resourceUrl, policy ) {
3443     	  hwc.traceEnteringMethod("hwc.MediaCache.getUrl");
3444    	  try {
3445    		  policy = policy ? policy : hwc.MediaCache.Policy.CACHE_FIRST;
3446    		  return getRequestUrl( "mediacache", "url=" + encodeURIComponent(resourceUrl)
3447    			 + "&policy=" + policy + "&bustCache=" + Math.random() );
3448    	  } finally {
3449    		  hwc.traceLeavingMethod("hwc.MediaCache.getUrl");
3450    	  }
3451       };
3452    
3453       /**
3454        * Represents an E2E Trace.  This object is used for debugging and analysis.
3455        * @classdesc
3456        */
3457       hwc.e2eTrace = {};
3458    
3459       hwc.e2eTrace.TraceLevel = {};
3460    
3461       /**
3462        * A constant indicating a high level of detail for the trace.
3463        * Use this level for functional analysis and detailed functional logging and tracing.
3464        * @type string
3465        * @memberOf hwc.e2eTrace
3466        */
3467       hwc.e2eTrace.TraceLevel.HIGH = "HIGH";
3468    
3469       /**
3470        * A constant indicating a low level of detail for the trace.
3471        * Use this level for response-time-distribution analysis: see how much time is spent on each server component to find bottlenecks.
3472        * @type string
3473        * @memberOf hwc.e2eTrace
3474        */
3475       hwc.e2eTrace.TraceLevel.LOW = "LOW";
3476    
3477       /**
3478        * A constant indicating a medium level of detail for the trace.
3479        * Use this level for performance analysis (performance traces are triggered on server-side).
3480        * @type string
3481        * @memberOf hwc.e2eTrace
3482        */
3483       hwc.e2eTrace.TraceLevel.MEDIUM = "MEDIUM";
3484    
3485       /**
3486        * Gets whether the e2e tracing has been requested to be started.
3487        * This function returns true between calls to {@link hwc.e2eTrace#startTrace} and {@link hwc.e2eTrace#stopTrace}.
3488        * @memberOf hwc.e2eTrace
3489        * @returns {boolean} True if trace is enabled, false otherwise.
3490        */
3491       hwc.e2eTrace.isTraceEnabled = function() {
3492     	  hwc.traceEnteringMethod("hwc.e2eTrace.isTraceEnabled");
3493    	  try {
3494    		  return parseBoolean(hwc.getDataFromContainer("e2etrace", "&method=istraceenabled"));
3495    	  } finally {
3496    		  hwc.traceLeavingMethod("hwc.e2eTrace.isTraceEnabled");
3497    	  }
3498       };
3499    
3500       /**
3501        * Sets the passport e2eTrace level.  This function must be called before {@link hwc.e2eTrace#startTrace}.
3502        *
3503        * @memberOf hwc.e2eTrace
3504        * @param {string} The trace level.  Must be one of {@link hwc.e2eTrace.TraceLevel.LOW}, {@link hwc.e2eTrace.TraceLevel.MEDIUM}, or
3505        * {@link hwc.e2eTrace.TraceLevel.HIGH}.
3506        */
3507       hwc.e2eTrace.setTraceLevel = function(level) {
3508     	  hwc.traceEnteringMethod("hwc.e2eTrace.setTraceLevel");
3509    	  try {
3510    		  hwc.getDataFromContainer("e2etrace", "&method=settracelevel&level=" + level);
3511    	  } finally {
3512    		  hwc.traceLeavingMethod("hwc.e2eTrace.setTraceLevel");
3513    	  }
3514       };
3515    
3516       /**
3517        * Starts tracing user actions and requests.  Before this function is called, the trace level must be set with {@link hwc.e2eTrace#setTracelevel}.
3518        * @memberOf hwc.e2eTrace
3519        */
3520       hwc.e2eTrace.startTrace = function() {
3521     	  hwc.traceEnteringMethod("hwc.e2eTrace.startTrace");
3522    	  try {
3523    		  hwc.getDataFromContainer("e2etrace", "&method=starttrace");
3524    	  } finally {
3525    		  hwc.traceLeavingMethod("hwc.e2eTrace.startTrace");
3526    	  }
3527       };
3528    
3529       /**
3530        * Stops tracing user actions and requests.
3531        * @memberOf hwc.e2eTrace
3532        */
3533       hwc.e2eTrace.stopTrace = function() {
3534     	  hwc.traceEnteringMethod("hwc.e2eTrace.stopTrace");
3535    	  try {
3536    		  hwc.getDataFromContainer("e2etrace", "&method=stoptrace");
3537    	  } finally {
3538    		  hwc.traceLeavingMethod("hwc.e2eTrace.stopTrace");
3539    	  }
3540       };
3541    
3542       /**
3543        * Upload the Business Transaction XML (BTX) to the server.
3544        * To upload, the SAP Solution Manager URL must be set in SAP Control Center configuration.
3545        * @memberOf hwc.e2eTrace
3546        * @returns {boolean} True if the upload is successful, false otherwise.
3547        */
3548       hwc.e2eTrace.uploadTrace = function() {
3549     	  hwc.traceEnteringMethod("hwc.e2eTrace.uploadTrace");
3550    	  try {
3551    		  return parseBoolean(hwc.getDataFromContainer("e2etrace", "&method=uploadtrace"));
3552    	  } finally {
3553    		  hwc.traceLeavingMethod("hwc.e2eTrace.uploadTrace");
3554    	  }
3555        };
3556    
3557       /**
3558        * Represents the Performance Manager.
3559        * @classdesc
3560        * @memberOf hwc
3561        * @example
3562        * // Start performance collection. 
3563        * if (hwc.perf.isEnabled())
3564        * {
3565        *     hwc.perf.stopInteraction();
3566        * }
3567        * 
3568        * hwc.perf.startInteraction('someinteraction');
3569        * 
3570        * hwc.perf.startInterval('IntervalName', 'CustomType'); // Start an optional interval.
3571        * 
3572        * // Stop performance collection.  Logs will be written.
3573        * if (hwc.perf.isEnabled())
3574        * {
3575        *   hwc.perf.stopInterval('IntervalName'); // Stop an optional interval.
3576        *   hwc.perf.stopInteraction();
3577        * }
3578        */
3579    hwc.perf = {};
3580    
3581       /**
3582        * Gets whether the performance agent is enabled.
3583        * @memberOf hwc.perf
3584        * @returns {boolean} True if the performance agent is enabled, false otherwise.
3585        */
3586       hwc.perf.isEnabled = function() {
3587     	  hwc.traceEnteringMethod("hwc.perf.isEnabled");
3588    	  try {
3589    		  return parseBoolean(hwc.getDataFromContainer("perf", "&method=isenabled"));
3590    	  } finally {
3591    		  hwc.traceLeavingMethod("hwc.perf.isEnabled");
3592    	  }
3593       };
3594    	  
3595       /**
3596        * Starts the interaction.
3597        * @memberOf hwc.perf
3598        * @param {string} interactionName The name of the interaction.
3599        */
3600       hwc.perf.startInteraction = function(interactionName) {
3601     	  hwc.traceEnteringMethod("hwc.perf.startInteraction");
3602    	  try {
3603    		  hwc.getDataFromContainer("perf", "&method=startinteraction&interactionname=" + encodeURIComponent(interactionName));
3604    	  } finally {
3605    		  hwc.traceLeavingMethod("hwc.perf.startInteraction");
3606    	  }
3607       };
3608    	  
3609       /**
3610        * Stops the interaction.
3611        * @memberOf hwc.perf
3612        */
3613       hwc.perf.stopInteraction = function() {
3614     	  hwc.traceEnteringMethod("hwc.perf.stopInteraction");
3615    	  try {
3616    		  hwc.getDataFromContainer("perf", "&method=stopinteraction");
3617    	  } finally {
3618    		  hwc.traceLeavingMethod("hwc.perf.stopInteraction");
3619    	  }
3620       };
3621    	  
3622       /**
3623        * Starts an interval.
3624        * @memberOf hwc.perf
3625        * @param {string} intervalName The name of the interval.
3626        * @param {string} intervalType The type of the interval.\
3627        */
3628       hwc.perf.startInterval = function(intervalName, intervalType) {
3629     	  hwc.traceEnteringMethod("hwc.perf.startInterval");
3630    	  try {
3631    		  hwc.getDataFromContainer("perf", "&method=startinterval&intervalname=" + encodeURIComponent(intervalName) + "&intervaltype=" + encodeURIComponent(intervalType));
3632    	  } finally {
3633    		  hwc.traceLeavingMethod("hwc.perf.startInterval");
3634    	  }
3635       };
3636    	  
3637       /**
3638        * Stops the interval.
3639        * @memberOf hwc.perf
3640        * @param {string} intervalName The name of the interval.
3641        */
3642       hwc.perf.stopInterval = function(intervalName) {
3643     	  hwc.traceEnteringMethod("hwc.perf.stopInterval");
3644    	  try {
3645    		  hwc.getDataFromContainer("perf", "&method=stopinterval&intervalname=" + encodeURIComponent(intervalName));
3646    	  } finally {
3647    		  hwc.traceLeavingMethod("hwc.perf.stopInterval");
3648    	  }
3649       };
3650    
3651       /**
3652        * Internal function to parse a boolean
3653        * @private
3654        */
3655       function parseBoolean(val)
3656       {
3657          return val === 'true';
3658       }
3659    })(hwc);
3660    
3661    /**
3662     * Used to group anonymous objects and callback functions used as method parameters. Methods and fields in this
3663     * namespace cannot be instantiated. Used for API docs generation only.
3664     * @namespace
3665     */
3666    anonymous = (typeof anonymous === "undefined" || !anonymous) ? {} : anonymous;      // SUP 'namespace'
3667    
3668    
3669    /**
3670     * Callback function that will be invoked when the connection state changes.  Connection listeners can be added with {@link hwc.addConnectionListener}.
3671     *
3672     * @name anonymous.ConnectionStateListener
3673     *
3674     * @param {number} event A number indicating the event that occurred (will be {@link hwc.CONNECTED} or {@link hwc.DISCONNECTED}).
3675     * @param {number} errorCode An error code (0 indicating success).
3676     * @param {string} errorMessage Text of the error message.  Will be empty of there is no error.
3677     *
3678     * @function
3679     */
3680    
3681    /**
3682     * Callback function that will be invoked when events are logged to the event log.  Log listeners can be added with {@link hwc.addLogListener}.
3683     *
3684     * @name anonymous.LogListener
3685     *
3686     * @param {number} milliseconds The date of the log message represented in milliseconds.
3687     * @param {number} event A number that represents which category this event falls under (It will be one of {@link hwc.CONNECTION_ERROR},
3688     * {@link hwc.CONNECTION_OTHER}, {@link hwc.CONNECTION_CONNECTED}, {@link hwc.CONNECTION_DISCONNECTED}, {@link hwc.CONNECTION_RETRIEVED_ITEMS}).
3689     * @param {string} optionalString The string carrying the message of the log event.
3690     *
3691     * @function
3692     */
3693    
3694    /**
3695     * Callback function that will be invoked on hybrid app installation events.  App installation listeners can be added with
3696     * {@link hwc.addAppInstallationListener}.
3697     *
3698     * @name anonymous.AppInstallationListener
3699     *
3700     * @param {number} event A number indicating the event (will be either {@link hwc.INSTALLATION_BEGIN} or {@link hwc.INSTALLATION_END}).
3701     * @param {string} moduleId The module ID of the hybrid app the event is about.
3702     * @param {string} version The version of the hybrid app the event is about.
3703     * @param {string} moduleName The display name of the hybrid app the event is about.
3704     *
3705     * @function
3706     */
3707    
3708    /**
3709     * Callback function that will be invoked when push notifications are available.
3710     * Push notification listeners can be added with {@link hwc.addPushNotificationListener}.
3711     *
3712     * @name anonymous.PushNotificationListener
3713     *
3714     * @param {Array} notifications An array of notifications.
3715     *
3716     * @returns {number} A number indicating whether other push notification listeners should be called after this one.
3717     * Must be either {@link hwc.NOTIFICATION_CANCEL} (if no more listener callbacks should be called) or {@link hwc.NOTIFICATION_CONTINUE}
3718     * (if more listener callbacks should be called).
3719     *
3720     * Callback function that will be invoked on hybrid app installation events.
3721     * @name anonymous.AppInstallationListener
3722     * @param {Integer} event            Installation flags including, BEGIN(1), END(2), FAIL(3)
3723     * @param {String} moduleId          Optional Module Id
3724     * @param {String} version           Optional Module version
3725     * @param {String} moduleName        Optional Module display name
3726     * @param {String} designerVersion   Optional Version of designer used to create app
3727     * @param {String} containerVersion  Optional Version of hybrid web container
3728     * @callback
3729     * @function
3730     */
3731       /**
3732        * Callback function that will be invoked on hybrid app installation events.
3733        * @name anonymous.AppInstallationListener
3734        * @param {Integer} event            Installation flags including, BEGIN(1), END(2)
3735        * @param {String} moduleId          Optional Module Id
3736       	* @param {String} version           Optional Module version
3737       	* @param {String} moduleName        Optional Module display name
3738       	* @callback
3739       	* @function
3740        */
3741    
3742    /**
3743     * Callback function that will be invoked on hybrid app events.
3744     * Application listeners can be added with {@link hwc.addAppListener}.
3745     *
3746     * @name anonymous.ApplicationListener
3747     *
3748     * @param {number} event A number indicating what event has taken place (will be one of {@link hwc.APP_REFRESH},
3749     * {@link hwc.APP_ADDED}, {@link hwc.APP_UPDATED}, {@link hwc.APP_REMOVED}).
3750     * @param {number} moduleId The module id of the hyrbid app the event is about.
3751     * @param {number} version module The version of the hybrid app the event is about.
3752     *
3753     * @function
3754     */
3755    
3756    /**
3757     * Callback function that will be invoked on message events.  Message listeners can be added with {@link hwc.addMessageListener}.
3758     *
3759     * @name anonymous.MessageListener
3760     *
3761     * @param {number} flag A number indicating which message event occured (will be one of {@link hwc.MSG_ADDED}, {@link hwc.MSG_REMOVED},
3762     * {@link hwc.MSG_UPDATED}, {@link hwc.MSG_REFRESH}).
3763     * @param {number} msgId The message id of the affected message.
3764     *
3765     * @function
3766     */
3767