hwc-api.js

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