source: branches/2.2/jabberit_messenger/jmessenger/js/trophyim.js @ 3120

Revision 3120, 70.2 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #1091 - Implementado a busca de salas para bate-papo no novo modulo Expresso messenger XEP-0045-MUC.

  • Property svn:executable set to *
Line 
1/**
2 *   This program is distributed under the terms of the MIT license.
3 *   Please see the LICENSE file for details.
4 *
5 *   Copyright 2008 Michael Garvin
6 */
7
8var TROPHYIM_BOSH_SERVICE       = "/proxy/ejabberd";  //Change to suit
9
10var TROPHYIM_LOG_LINES          = 200;
11
12var TROPHYIM_LOGLEVEL           = 0; //0=debug, 1=info, 2=warn, 3=error, 4=fatal
13
14var TROPHYIM_VERSION            = "0.3";
15
16var TROPHYIM_RESOURCE           = "/JABBERITWEB";
17
18var TROPHYIM_CHATROOM           = "conference.im.pr.gov.br";
19
20//Uncomment to make session reattachment work
21//var TROPHYIM_JSON_STORE = "json_store.php";
22
23/** Object: DOMObjects
24 *  This class contains builders for all the DOM objects needed by TrophyIM
25 */
26DOMObjects = {
27    /** Function: xmlParse
28     *  Cross-browser alternative to using innerHTML
29     *  Parses given string, returns valid DOM HTML object
30     *
31     *  Parameters:
32     *    (String) xml - the xml string to parse
33     */
34    xmlParse : function(xmlString) {
35        var xmlObj = this.xmlRender(xmlString);
36        if(xmlObj) {
37            try { //Firefox, Gecko, etc
38                if (this.processor == undefined) {
39                    this.processor = new XSLTProcessor();
40                    this.processor.importStylesheet(this.xmlRender(
41                    '<xsl:stylesheet version="1.0"\
42                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
43                    <xsl:output method="html" indent="yes"/><xsl:template\
44                    match="@*|node()"><xsl:copy><xsl:copy-of\
45                    select="@*|node()"/></xsl:copy></xsl:template>\
46                    </xsl:stylesheet>'));
47                }
48                var htmlObj =
49                this.processor.transformToDocument(xmlObj).documentElement;
50                //Safari has a quirk where it wraps dom elements in <html><body>
51                if (htmlObj.tagName.toLowerCase() == 'html') {
52                    htmlObj = htmlObj.firstChild.firstChild;
53                }
54                return document.importNode(htmlObj, true);
55            } catch(e) {
56                try { //IE is so very very special
57                    var htmlObj = document.importNode(xmlObj.documentElement, true);
58                    if (htmlObj.tagName.toLowerCase() == "div") {
59                        var div_wrapper = document.createElement('div');
60                        div_wrapper.appendChild(htmlObj);
61                        if(div_wrapper.innerHTML) {
62                            div_wrapper.innerHTML = div_wrapper.innerHTML;
63                        }
64                        htmlObj = div_wrapper.firstChild;
65                    }
66                    return htmlObj;
67                } catch(e) {
68                    alert("TrophyIM Error: Cannot add html to page " + e.message);
69                }
70            }
71        }
72    },
73    /** Function: xmlRender
74     *  Uses browser-specific methods to turn given string into xml object
75     *
76     *  Parameters:
77     *    (String) xml - the xml string to parse
78     */
79    xmlRender : function(xmlString) {
80        try {//IE
81            var renderObj = new ActiveXObject("Microsoft.XMLDOM");
82            renderObj.async="false";
83            if(xmlString) {
84                renderObj.loadXML(xmlString);
85            }
86        } catch (e) {
87            try { //Firefox, Gecko, etc
88                if (this.parser == undefined) {
89                    this.parser = new DOMParser();
90                }
91                var renderObj = this.parser.parseFromString(xmlString,
92                "application/xml");
93            } catch(e) {
94                alert("TrophyIM Error: Cannot create new html for page");
95            }
96        }
97
98        return renderObj;
99    },
100    /** Function: getHTML
101     *  Returns named HTML snippet as DOM object
102     *
103     *  Parameters:
104     *    (String) name - name of HTML snippet to retrieve (see HTMLSnippets
105     *    object)
106     */
107    getHTML : function(page)
108        {
109        return this.xmlParse(HTMLSnippets[page]);
110    },
111       
112    /** Function: getScript
113     *  Returns script object with src to given script
114     *
115     *  Parameters:
116     *    (String) script - name of script to put in src attribute of script
117     *    element
118     */
119    getScript : function(script)
120        {
121        var newscript = document.createElement('script');
122        newscript.setAttribute('src', script);
123        newscript.setAttribute('type', 'text/javascript');
124        return newscript;
125    }
126};
127
128/** Object: TrophyIM
129 *
130 *  This is the actual TrophyIM application.  It searches for the
131 *  'trophyimclient' element and inserts itself into that.
132 */
133TrophyIM = {
134               
135
136        controll : { notificationNewUsers : 0 },       
137   
138        /** AutoConnection
139        *
140        */     
141               
142        autoConnection : { connect : true },
143
144        /** Object: chatHistory
145    *
146    *  Stores chat history (last 10 message) and current presence of active
147    *  chat tabs.  Indexed by jid.
148    */
149       
150        chatHistory : {},
151       
152        /** Constants:
153    *
154    *    (Boolean) stale_roster - roster is stale and needs to be rewritten.
155    */
156       
157        constants : {stale_roster: false},
158       
159        /** PosWindow
160         *
161         */     
162        posWindow : { left : 400, top : 100 }, 
163               
164        /** StatusConnection
165         *
166         */
167
168        statusConn : { connected : false },
169       
170        /** TimeOut Render Roster
171         *
172         *
173         */
174       
175        _timeOut : { renderRoster : null },
176       
177     /** Function: setCookie
178     *
179     *  Sets cookie name/value pair.  Date and path are auto-selected.
180     *
181     *  Parameters:
182     *    (String) name - the name of the cookie variable
183     *    (String) value - the value of the cookie variable
184     */
185   
186        setCookie : function(name, value)
187        {
188        var expire = new Date();
189        expire.setDate(expire.getDate() + 365);
190        document.cookie = name + "=" + value + "; expires=" + expire.toGMTString();
191    },
192   
193        /** Function: delCookie
194     *
195     *  Deletes cookie
196     *
197     *  Parameters:
198     *    (String) name) - the name of the cookie to delete
199     */
200   
201        delCookie : function(name)
202        {
203        var expire = new Date();
204        expire.setDate(expire.getDate() - 365);
205        document.cookie = name + "= ; expires=" + expire.toGMTString();
206        delete TrophyIM.cookies[name];
207    },
208   
209        /** Function: getCookies
210     *
211     *  Retrieves all trophyim cookies into an indexed object.  Inteneded to be
212     *  called once, at which time the app refers to the returned object instead
213     *  of re-parsing the cookie string every time.
214     *
215     *  Each cookie is also re-applied so as to refresh the expiry date.
216     */
217   
218        getCookies : function()
219        {
220        var cObj = {};
221        var cookies = document.cookie.split(';');
222       
223        for(var i = 0 ; i < cookies.length; i++ )
224        {
225                while ( cookies[i].charAt(0) == ' ')
226            {
227                cookies[i] = cookies[i].substring(1,cookies[i].length);
228            }
229               
230            if (cookies[i].substr(0, 8) == "trophyim")
231            {
232                var nvpair = cookies[i].split("=", 2);
233                cObj[nvpair[0]] = nvpair[1];
234                TrophyIM.setCookie(nvpair[0], nvpair[1]);
235            }
236        }
237       
238        return cObj;
239    },
240       
241    /** Function: load
242     *
243     *  This function searches for the trophyimclient div and loads the client
244     *  into it.
245     */
246
247        load : function()
248        {
249        if( loadscript.getUserCurrent() == null )
250        {
251                loadscript.setUserCurrent();     
252        }       
253
254        if ( !TrophyIM.statusConn.connected )
255                {
256                        TrophyIM.cookies = TrophyIM.getCookies();
257
258                        //Wait a second to give scripts time to load
259                        setTimeout( "TrophyIM.showLogin()", 550 );
260                }
261                else
262                {
263                        loadscript.rosterDiv();
264                }
265   },
266
267   /** Function: storeData
268     *
269     *  Store all our data in the JSONStore, if it is active
270     */
271     
272   storeData : function()
273   {
274        if ( TrophyIM.connection && TrophyIM.connection.connected )
275                {
276            TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
277            TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
278            TrophyIM.rosterObj.save();
279        }
280    },
281   
282    /**  Function: showlogin
283     *
284     *   This function clears out the IM box and either redisplays the login
285     *   page, or re-attaches to Strophe, preserving the logging div if it
286     *   exists, or creating a new one of we are re-attaching.
287     */
288     
289    showLogin : function()
290        {
291        /**
292         *
293         * JSON is the last script to load, so we wait on it
294                 * Added Strophe check too because of bug where it's sometimes missing
295                 *
296                 */
297
298                if ( typeof(JSON) != undefined && typeof(Strophe) != undefined )
299        {
300                TrophyIM.JSONStore = new TrophyIMJSONStore();
301               
302                        if ( TrophyIM.JSONStore.store_working && TrophyIM.cookies['trophyim_bosh_xid'] )
303            {
304                var xids = TrophyIM.cookies['trophyim_bosh_xid'].split("|");
305                TrophyIM.delCookie('trophyim_bosh_xid');
306                TrophyIM.constants.stale_roster = true;
307                       
308                                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
309                TrophyIM.connection.rawInput    = TrophyIM.rawInput;
310                TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
311                //Strophe.log = TrophyIM.log;
312                Strophe.info('Attempting Strophe attach.');
313                TrophyIM.connection.attach(xids[0], xids[1], xids[2], TrophyIM.onConnect);
314                TrophyIM.onConnect(Strophe.Status.CONNECTED);
315            }
316            else
317            {
318                // List Contact
319                                loadscript.rosterDiv();
320
321                                // Get User Current;
322                                var _getUserCurrent = null;
323                               
324                                var _flag       = 0;
325
326                                do
327                                {
328                                        _getUserCurrent = loadscript.getUserCurrent();
329                                        _flag++;
330                                       
331                                }while( ( _getUserCurrent == null || _flag > 3 ) )
332                                       
333                                TrophyIM.login( Base64.decode( _getUserCurrent.jid ), Base64.decode( _getUserCurrent.password ));
334            }
335        }
336        else
337        {
338                setTimeout("TrophyIM.showLogin()", 500);
339        }
340    },
341   
342        /** Function: log
343     *
344     *  This function logs the given message in the trophyimlog div
345     *
346     *  Parameter: (String) msg - the message to log
347     */
348   
349    log : function(level, msg)
350    {
351        if (TrophyIM.logging_div && level >= TROPHYIM_LOGLEVEL)
352        {
353            while(TrophyIM.logging_div.childNodes.length > TROPHYIM_LOG_LINES)
354            {
355                TrophyIM.logging_div.removeChild( TrophyIM.logging_div.firstChild );
356            }
357           
358            var msg_div = document.createElement('div');
359            msg_div.className = 'trophyimlogitem';
360            msg_div.appendChild(document.createTextNode(msg));
361           
362            TrophyIM.logging_div.appendChild(msg_div);
363            TrophyIM.logging_div.scrollTop = TrophyIM.logging_div.scrollHeight;
364        }
365    },
366       
367    /** Function: rawInput
368     *
369     *  This logs the packets actually recieved by strophe at the debug level
370     */
371    rawInput : function (data)
372        {
373        Strophe.debug("RECV: " + data);
374    },
375       
376    /** Function: rawInput
377     *
378     *  This logs the packets actually recieved by strophe at the debug level
379     */
380    rawOutput : function (data)
381        {
382        Strophe.debug("SEND: " + data);
383    },
384       
385    /** Function: login
386     *
387     *  This function logs into server using information given on login page.
388     *  Since the login page is where the logging checkbox is, it makes or
389     *  removes the logging div and cookie accordingly.
390     *
391     */
392    login : function()
393        {
394                if ( TrophyIM.JSONStore.store_working )
395                {
396                   //In case they never logged out
397            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat', 'chat_history']);
398        }
399
400                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
401        TrophyIM.connection.rawInput    = TrophyIM.rawInput;
402        TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
403        //Strophe.log                                   = TrophyIM.log;
404       
405                if ( arguments.length > 0 )
406                {
407                        var barejid = arguments[0];
408                        var password = arguments[1];
409                       
410                        TrophyIM.connection.connect( barejid + TROPHYIM_RESOURCE, password, TrophyIM.onConnect );
411                }
412                else
413                {
414                       
415                        var barejid             = document.getElementById('trophyimjid').value
416                        var fulljid             = barejid + TROPHYIM_RESOURCE;
417                        var password    = document.getElementById('trophyimpass').value;
418                        var button              = document.getElementById('trophyimconnect');
419                       
420                        loadscript.setUserCurrent( barejid, password);
421                       
422                        if ( button.value == 'connect' )
423                        {
424                                button.value = 'disconnect';
425                                //TrophyIM.connection.connect( fulljid , password, TrophyIM.onConnect );
426                               
427                                TrophyIM.login( barejid, password );
428                                _winBuild('window_login_page', 'remove');
429                        }
430                }
431
432                TrophyIM.setCookie('trophyimjid', barejid);
433    },
434       
435    /** Function: logout
436     *
437     *  Logs into fresh session through Strophe, purging any old data.
438     */
439    logout : function()
440        {
441        TrophyIM.autoConnection.connect = false;
442       
443        TrophyIM.delCookie('trophyim_bosh_xid');
444       
445        delete TrophyIM['cookies']['trophyim_bosh_xid'];
446       
447        TrophyIM.connection.disconnect();
448    },
449       
450    /** Function onConnect
451     *
452     *  Callback given to Strophe upon connection to BOSH proxy.
453     */
454    onConnect : function(status)
455        {
456        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
457               
458        if( status == Strophe.Status.CONNECTING )
459                {
460                loading_gif.style.display = "block";
461                Strophe.info('Strophe is connecting.');
462        }
463               
464                if( status == Strophe.Status.CONNFAIL )
465                {
466                        TrophyIM.delCookie('trophyim_bosh_xid');
467            TrophyIM.statusConn.connected = false;
468            loading_gif.style.display = "block";
469        }
470               
471                if( status == Strophe.Status.DISCONNECTING )
472                {
473                        TrophyIM.statusConn.connected = false;
474        }
475               
476                if( status == Strophe.Status.DISCONNECTED )
477                {
478                        if( TrophyIM.autoConnection.connect )
479                        {
480                                loading_gif.style.display = "block";
481                               
482                                TrophyIM.delCookie('trophyim_bosh_xid');
483                   
484                    TrophyIM.statusConn.connected = false;
485                   
486                                setTimeout(function()
487                                {
488                            TrophyIM.showLogin();
489                           
490                                },10000);
491                               
492                    loadscript.clrAllContacts();       
493                   
494                    loadscript.setStatusJabber(i18n.STATUS_ANAVAILABLE,"unavailable");
495                   
496                    delete TrophyIM.rosterObj.roster;
497                    delete TrophyIM.rosterObj.groups;
498                        }
499        }
500               
501                if( status == Strophe.Status.CONNECTED )
502                {
503                        loadscript.setStatusJabber(i18n.STATUS_AVAILABLE,'available');
504                        TrophyIM.statusConn.connected = true;
505            TrophyIM.showClient();
506        }
507    },
508
509    /** Function: showClient
510     *
511     *  This clears out the main div and puts in the main client.  It also
512     *  registers all the handlers for Strophe to call in the client.
513     */
514    showClient : function()
515        {
516        TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
517        TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
518               
519        TrophyIM.rosterObj = new TrophyIMRoster();
520        TrophyIM.connection.addHandler(TrophyIM.onVersion, Strophe.NS.VERSION, 'iq', null, null, null);
521        TrophyIM.connection.addHandler(TrophyIM.onRoster, Strophe.NS.ROSTER, 'iq', null, null, null);
522        TrophyIM.connection.addHandler(TrophyIM.onPresence, null, 'presence', null, null, null);
523        TrophyIM.connection.addHandler(TrophyIM.onMessage, null, 'message', null, null,  null);
524       
525                //Get roster then announce presence.
526        TrophyIM.connection.send($iq({type: 'get', xmlns: Strophe.NS.CLIENT}).c('query', {xmlns: Strophe.NS.ROSTER}).tree());
527        TrophyIM.connection.send($pres().tree());
528                setTimeout( TrophyIM.renderRoster, 1000);
529    },
530       
531    /** Function: clearClient
532     *
533     *  Clears out client div, preserving and returning existing logging_div if
534     *  one exists
535     */
536     
537    clearClient : function()
538    {
539        if(TrophyIM.logging_div)
540        {
541            var logging_div = TrophyIM.client_div.removeChild(document.getElementById('trophyimlog'));
542        }
543        else
544        {
545            var logging_div = null;
546        }
547       
548        while(TrophyIM.client_div.childNodes.length > 0)
549        {
550            TrophyIM.client_div.removeChild(TrophyIM.client_div.firstChild);
551        }
552       
553        return logging_div;
554    },
555   
556    /** Function: onVersion
557     *
558     *  jabber:iq:version query handler
559     */
560     
561    onVersion : function(msg)
562    {
563        Strophe.debug("Version handler");
564        if (msg.getAttribute('type') == 'get')
565        {
566            var from = msg.getAttribute('from');
567            var to = msg.getAttribute('to');
568            var id = msg.getAttribute('id');
569            var reply = $iq({type: 'result', to: from, from: to, id: id}).c('query',
570            {name: "TrophyIM", version: TROPHYIM_VERSION, os:
571            "Javascript-capable browser"});
572            TrophyIM.connection.send(reply.tree());
573        }
574        return true;
575    },
576   
577    /** Function: onRoster
578     *
579     *  Roster iq handler
580     */
581   
582    onRoster : function(msg)
583        {
584        var roster_items = msg.firstChild.getElementsByTagName('item');
585               
586                for (var i = 0; i < roster_items.length; i++)
587                {
588                        with(roster_items[i])
589                        {
590                                var groups              = getElementsByTagName('group');       
591                                var group_array = [];
592                               
593                                for( var g = 0 ; g < groups.length; g++ )
594                                {
595                                        if( groups[g].hasChildNodes() )
596                                                group_array[group_array.length] = groups[g].firstChild.nodeValue;
597                                }
598
599                                if( getAttribute('ask') && getAttribute('ask').toString() === "subscribe" )
600                                {
601                                        if( getAttribute('subscription').toString() === "none" )
602                                        {
603                                                TrophyIM.rosterObj.addContact( getAttribute('jid'), getAttribute('ask'), getAttribute('name'), group_array );
604                                        }
605                                       
606                                        if( getAttribute('subscription').toString() === "remove" )
607                                        {
608                                                TrophyIM.rosterObj.removeContact( getAttribute('jid').toString() );
609                                        }
610                                }
611                                else
612                                {
613                                        if( ( getAttribute('ask') == null && getAttribute('subscription').toString() === "remove" ) || getAttribute('subscription').toString() === "remove" )
614                                        {
615                                                TrophyIM.rosterObj.removeContact( getAttribute('jid').toString() );
616                                        }
617                                        else
618                                        {
619                                                TrophyIM.rosterObj.addContact( getAttribute('jid'), getAttribute('subscription'), getAttribute('name'), group_array );
620                                        }
621                                }
622                        }
623        }
624
625                if ( msg.getAttribute('type') == 'set' )
626                {
627                        var _iq = $iq({type: 'reply', id: msg.getAttribute('id'), to: msg.getAttribute('from')});
628                        TrophyIM.connection.send( _iq.tree());
629        }
630       
631                return true;
632    },
633   
634    /** Function: onPresence
635     *
636     *  Presence Handler
637     */
638   
639    onPresence : function(msg)
640        {
641        // Get Presences ChatRoom
642        TrophyIM.onPresenceChatRoom( msg );
643
644        var type                = msg.getAttribute('type') ? msg.getAttribute('type') : 'available';
645        var show                = msg.getElementsByTagName('show').length ? Strophe.getText(msg.getElementsByTagName('show')[0]) : type;
646        var status              = msg.getElementsByTagName('status').length ? Strophe.getText(msg.getElementsByTagName('status')[0]) : '';
647        var priority    = msg.getElementsByTagName('priority').length ? parseInt(Strophe.getText(msg.getElementsByTagName('priority')[0])) : 0;
648
649        if( msg.getAttribute('from').toString().indexOf( TROPHYIM_CHATROOM ) < 0 )
650        {       
651                TrophyIM.rosterObj.setPresence( msg.getAttribute('from'), priority, show, status );
652        }
653       
654        return true;
655    },
656
657    /** Function : onPresenceChatRoom
658     *
659     * Presence ChatRoom Handler
660     */
661   
662    onPresenceChatRoom : function(msg)
663    {
664        var xquery = msg.getElementsByTagName("x");
665       
666        if ( xquery.length > 0 )
667        {
668                for ( var i = 0; i < xquery.length; i++ )
669            {
670                var xmlns = xquery[i].getAttribute("xmlns");
671               
672                if( xmlns.indexOf("http://jabber.org/protocol/muc#user") == 0 )
673                {
674                        var _from       = xquery[i].parentNode.getAttribute('from');
675                        var _to         = xquery[i].parentNode.getAttribute('to');
676
677                        // Get NameChatRoom
678                        var nameChatRoom        = Strophe.getBareJidFromJid( _from );
679                       
680                        // Get nickName
681                        var nickName            = Strophe.getResourceFromJid( _from );
682                       
683                        var type        = ( xquery[i].parentNode.getAttribute('type') != null ) ? xquery[i].parentNode.getAttribute('type') : 'available' ;
684                        var show        = type;
685                       
686                        var _idElement = nameChatRoom + "_UserChatRoom__" + nickName;
687                         
688                        var _UserChatRoom               = document.createElement("div");
689                                _UserChatRoom.id        = _idElement;
690                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");
691                                _UserChatRoom.appendChild( document.createTextNode(nickName) );
692
693                        var nodeUser = document.getElementById( _idElement );   
694                               
695                        if( nodeUser == null )
696                        {
697                                if( document.getElementById( nameChatRoom + '__roomChat__participants' ) != null )
698                                {
699                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
700                                        nameChatRoom.appendChild( _UserChatRoom );
701                                }
702                                else
703                                {
704                                        TrophyIM.makeChatRoom( nameChatRoom, nameChatRoom.substring(0, nameChatRoom.indexOf('@')));
705                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
706                                        nameChatRoom.appendChild( _UserChatRoom );
707                                }
708                        }
709                        else
710                        {
711                                if( type == 'unavailable' )
712                                {
713                                        nodeUser.parentNode.removeChild( nodeUser );
714                                }
715                                else if( show )
716                                {
717                                        nodeUser.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");       
718                                }
719                        }
720                }
721               
722                /*if( xmlns.indexOf("http://jabber.org/protocol/muc#user") == 0 )
723                {
724                        var nameChatRoom = xquery[i].parentNode.getAttribute('from');
725                                nameChatRoom = Strophe.getBareJidFromJid(nameChatRoom);
726
727                        var nickName = xquery[i].parentNode.getAttribute('from');
728                                nickName = Strophe.getResourceFromJid(nickName);
729
730                        var type = ( xquery[i].parentNode.getAttribute('type') != null ) ? xquery[i].parentNode.getAttribute('type') : 'available' ;
731                       
732                        var show = ( xquery[i].parentNode.firstChild.firstChild.nodeName.toLowerCase() == "show" ) ? xquery[i].parentNode.firstChild.firstChild.nodeValue : type ;
733                       
734                        if( xquery[i].firstChild.getAttribute('jid') )
735                        {
736                                if ( Strophe.getBareJidFromJid( xquery[i].firstChild.getAttribute('jid') ) == Strophe.getBareJidFromJid( TrophyIM.connection.jid ) )
737                                        show = loadscript.getStatusUserIM();
738                        }
739                       
740                        var _UserChatRoom = document.createElement("div");
741                                _UserChatRoom.id = nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid');
742                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");
743                                _UserChatRoom.appendChild( document.createTextNode(nickName) );
744               
745                        var nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') );         
746                               
747                        if( nodeUser == null && xquery[i].firstChild.getAttribute('jid') )
748                        {
749                                if( document.getElementById( nameChatRoom + '__roomChat__participants' ) != null )
750                                {
751                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
752                                        nameChatRoom.appendChild( _UserChatRoom );
753                                }
754                                else
755                                {
756                                        TrophyIM.makeChatRoom( nameChatRoom, nameChatRoom );
757                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
758                                        nameChatRoom.appendChild( _UserChatRoom );
759                                }
760                        }
761                        else
762                        {
763                                if( type == 'unavailable' )
764                                {
765                                        var nodeUser = "";
766                                       
767                                        if( xquery[i].firstChild.getAttribute('jid') != null )
768                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') );
769                                        else
770                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].parentNode.getAttribute('to') );
771                                       
772                                        nodeUser.parentNode.removeChild( nodeUser );
773                                }
774                                else if( show )
775                                {
776                                        var _UserChatRoom = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') )
777                                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");   
778                                }
779                        }
780                }*/
781            }
782        }
783    },   
784   
785    /** Function: onMessage
786     *
787     *  Message handler
788     */
789   
790    onMessage : function(msg)
791    {
792        var checkTime = function(i)
793        {
794                if ( i < 10 ) i= "0" + i;
795               
796                return i;
797        };
798       
799                var messageDate = function( _date )
800                {
801                        var _dt = _date.substr( 0, _date.indexOf( 'T' ) ).split( '-' );
802                        var _hr = _date.substr( _date.indexOf( 'T' ) + 1, _date.length - _date.indexOf( 'T' ) - 2 ).split( ':' );
803                       
804                        ( _date = new Date ).setTime( Date.UTC( _dt[0], _dt[1] - 1, _dt[2], _hr[0], _hr[1], _hr[2] ) );
805
806                        return ( _date.toLocaleDateString( ).replace( /-/g, '/' ) + ' ' + _date.toLocaleTimeString( ) );
807                };
808
809        var data        = new Date();
810        var dtNow       = checkTime(data.getHours()) + ":" + checkTime(data.getMinutes()) + ":" + checkTime(data.getSeconds());
811       
812        var from        = msg.getAttribute('from');
813        var type        = msg.getAttribute('type');
814        var elems       = msg.getElementsByTagName('body');
815        var delay       = ( msg.getElementsByTagName('delay') ) ? msg.getElementsByTagName('delay') : null;
816        var stamp       = ( delay[0] != null ) ? "<font style='color:red;'>" + messageDate(delay[0].getAttribute('stamp')) + "</font>" :  dtNow;
817
818                var barejid             = Strophe.getBareJidFromJid(from);
819                var jidChatRoom = Strophe.getResourceFromJid(from);
820                var jid_lower   = barejid.toLowerCase();
821                var contact             = "";
822                var state               = "";
823
824                var chatBox     = document.getElementById(jid_lower + "__chatState");
825                var chatStateOnOff = null;
826                var active      = msg.getElementsByTagName('active');
827               
828                contact = barejid.toLowerCase();
829                contact = contact.substring(0, contact.indexOf('@'));
830           
831                if( TrophyIM.rosterObj.roster[barejid] )
832                {
833                        if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
834                        {
835                                contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
836                        }
837                }
838
839                // Message with body are "content message", this means state active
840                if ( elems.length > 0 )
841                {
842                        state = "";
843                       
844                        // Set notify chat state capability on when sender notify it themself
845                        chatStateOnOff = document.getElementById(jid_lower + "__chatStateOnOff");
846                       
847                        if (active.length > 0 & chatStateOnOff != null )
848                        {
849                                chatStateOnOff.value = 'on';
850                        }
851
852                        // Get Message
853                        var _message = document.createElement("div");
854                        _message.innerHTML = Strophe.getText(elems[0]);
855                       
856                        var scripts = _message.getElementsByTagName('script');
857                       
858                        for (var i = 0; i < scripts.length; i++)
859                                _message.removeChild(scripts[i--]);
860                       
861                        _message.innerHTML = _message.innerHTML.replace(/^\s+|\s+$|^\n|\n$/g, "");
862                       
863                        // Get Smiles
864                        _message.innerHTML = loadscript.getSmiles( _message.innerHTML );
865
866                        if (type == 'chat' || type == 'normal')
867                        {
868                                if ( _message.hasChildNodes() )
869                                {
870                                        var message =
871                                        {
872                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + contact + "</font>",
873                                msg             : "</br>" + _message.innerHTML
874                        };
875                                       
876                                        TrophyIM.addMessage( TrophyIM.makeChat( from ), jid_lower, message );
877                                }
878                        }
879                        else if( type == 'groupchat')
880                        {
881                                if ( _message.hasChildNodes() )
882                                {
883                                        var message =
884                                        {
885                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + jidChatRoom + "</font>",
886                                msg             : "</br>" + _message.innerHTML
887                        };
888
889                                        TrophyIM.addMessage( TrophyIM.makeChatRoom( barejid ), jid_lower, message );
890                                }
891                        }
892                }
893                // Message without body are "content message", this mean state is not active
894                else
895                {
896                        if( chatBox != null )
897                                state = TrophyIM.getChatState(msg);                     
898                }
899               
900                // Clean chat status message some time later           
901                var clearChatState = function()
902                {
903                        chatBox.innerHTML='';
904                }
905               
906                if (chatBox != null)
907                {
908                        var clearChatStateTimer;
909                       
910                        chatBox.innerHTML = "<font style='font-weight:bold; color:grey; float:right;'>" + state + "</font>";
911                       
912                        var _composing =  msg.getElementsByTagName('composing');
913                       
914                        if ( _composing.length == 0 )
915                               
916                                clearChatStateTimer = setTimeout(clearChatState, 2000);
917                        else
918                                clearTimeout(clearChatStateTimer);                     
919                }
920
921                return true;
922        },
923
924        /** Function: getChatState
925         *
926         *  Parameters:
927         *    (string) msg - the message to get chat state
928         *    (string) jid - the jid of chat box to update the chat state to.
929         */
930        getChatState : function(msg)
931        {
932                var     state =  msg.getElementsByTagName('inactive');
933               
934                if ( state.length > 0 )
935                {
936                return i18n.INACTIVE;
937                }
938                else
939                {
940                state = msg.getElementsByTagName('gone');
941            if ( state.length > 0 )
942            {
943                return i18n.GONE;
944                        }
945            else
946            {
947                state = msg.getElementsByTagName('composing');
948                if ( state.length > 0 )
949                {
950                        return i18n.COMPOSING;
951                                }
952                else
953                {
954                        state =  msg.getElementsByTagName('paused');
955                        if ( state.length > 0 )
956                        {
957                                return i18n.PAUSED;
958                                        }
959                                }
960                        }
961                }
962               
963                return '';
964        },
965
966        /** Function: makeChat
967     *
968     *  Make sure chat window to given fulljid exists, switching chat context to
969     *  given resource.
970     */
971     
972    makeChat : function(fulljid)
973    {
974        var barejid             = Strophe.getBareJidFromJid(fulljid);
975        var titleWindow = "";
976
977        var paramsChatBox =
978        {
979                        'enabledPopUp'  : ( ( loadscript.getIsIE() ) ? "none" : "block" ),
980                        'idChatBox'     : barejid + "__chatBox",
981                        'jidTo'                 : barejid,
982                                'path_jabberit' : path_jabberit
983        };
984
985        titleWindow = barejid.toLowerCase();
986                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
987
988        if( TrophyIM.rosterObj.roster[barejid] )
989        {
990            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
991            {
992                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
993            }
994        }
995
996        // Position Top
997        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
998        if( TrophyIM.posWindow.top > 200 )
999                TrophyIM.posWindow.top  = 100;
1000       
1001        // Position Left
1002        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
1003        if( TrophyIM.posWindow.left > 455 )
1004                TrophyIM.posWindow.left = 400;
1005       
1006        var _content = document.createElement( 'div' );
1007        _content.innerHTML = loadscript.parse( "chat_box", "chatBox.xsl", paramsChatBox);
1008        _content = _content.firstChild;
1009       
1010        var _messages           = _content.firstChild.firstChild;
1011        var _textarea           = _content.getElementsByTagName( 'textarea' ).item( 0 );
1012        var _send                       = _content.getElementsByTagName( 'input' ).item( 0 );
1013                var _chatStateOnOff     = _content.getElementsByTagName( 'input' ).item( 1 );
1014
1015        var _send_message = function( )
1016        {
1017                if ( ! TrophyIM.sendMessage( barejid, _textarea.value ) )
1018                        return false;
1019
1020                // Add Message in chatBox;
1021                TrophyIM.addMessage( _messages, barejid, {
1022                        contact : "<font style='font-weight:bold; color:red;'>" + i18n.ME + "</font>",
1023                        msg : "<br/>" + _textarea.value
1024                } );
1025
1026                _textarea.value = '';
1027                _textarea.focus( );
1028        };
1029               
1030                var composingTimer_ = 0;
1031                var isComposing_ = 0;
1032                var timeCounter;
1033
1034                var setComposing = function( )
1035                {
1036                        var checkComposing = function()
1037                        {
1038                if (!isComposing_) {
1039                        // User stopped composing
1040                        composingTimer_ = 0;
1041                        clearInterval(timeCounter);
1042                        TrophyIM.sendContentMessage(barejid, 'paused');
1043                } else {
1044                        TrophyIM.sendContentMessage(barejid, 'composing');
1045                }
1046                isComposing_ = 0; // Reset composing
1047                }
1048
1049                if (!composingTimer_) {
1050                /* User (re)starts composing */
1051                composingTimer_ = 1;
1052                timeCounter = setInterval(checkComposing,4000);
1053                }
1054                isComposing_ = 1;
1055        };
1056
1057        loadscript.configEvents( _send, 'onclick', _send_message );
1058                loadscript.configEvents( _textarea, 'onkeyup', function( e )
1059                {
1060                        if ( e.keyCode == 13 ){
1061                                _send_message( );
1062                                // User stopped composing
1063                composingTimer_ = 0;
1064                clearInterval(timeCounter);
1065                        }else{
1066                                if (_chatStateOnOff.value == 'on')
1067                                        setComposing();
1068                        }
1069                } );       
1070
1071        var winChatBox =
1072        {
1073                         id_window              : "window_chat_area_" + barejid,
1074                         barejid                : barejid,
1075                         width                  : 387,
1076                         height                 : 375,
1077                         top                    : TrophyIM.posWindow.top,
1078                         left                   : TrophyIM.posWindow.left,
1079                         draggable              : true,
1080                         visible                : "display",
1081                         resizable              : true,
1082                         zindex                 : loadscript.getZIndex(),
1083                         title                  : titleWindow,
1084                         closeAction    : "hidden",
1085                         content                : _content     
1086        }
1087       
1088                _win = _winBuild(winChatBox);
1089
1090        // Notification New Message
1091        loadscript.notification(barejid);
1092       
1093        // Photo User;
1094                loadscript.getPhotoUser(barejid);
1095               
1096                _textarea.focus( );
1097               
1098                return ( _messages = _win.content( ).firstChild );
1099    },
1100
1101        /** Function: makeChatRoom
1102    *
1103    *
1104    *
1105    */
1106   
1107    makeChatRoom : function()
1108    {
1109        var jidChatRoom = arguments[0];
1110        var titleWindow = "ChatRoom - " + arguments[1];
1111       
1112        var paramsChatRoom =
1113        {
1114                        'idChatRoom'    : jidChatRoom + "__roomChat",
1115                        'jidTo'                 : jidChatRoom,
1116                        'lang_Send'             : i18n.SEND,
1117                        'lang_Leave_ChatRoom' : i18n.LEAVE_CHATROOM,
1118                                'path_jabberit' : path_jabberit
1119        };
1120
1121        // Position Top
1122        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
1123        if( TrophyIM.posWindow.top > 200 )
1124                TrophyIM.posWindow.top  = 100;
1125       
1126        // Position Left
1127        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
1128        if( TrophyIM.posWindow.left > 455 )
1129                TrophyIM.posWindow.left = 400;
1130
1131        var _content = document.createElement( 'div' );
1132        _content.innerHTML = loadscript.parse( "chat_room", "chatRoom.xsl", paramsChatRoom );
1133        _content = _content.firstChild;
1134       
1135        var _messages           = _content.firstChild.firstChild;
1136        var _textarea           = _content.getElementsByTagName( 'textarea' ).item( 0 );
1137        var _send                       = _content.getElementsByTagName( 'input' ).item( 0 );
1138        var _leaveChatRoom      = _content.getElementsByTagName( 'input' ).item( 1 );
1139       
1140        var _send_message = function( )
1141        {
1142                if ( ! TrophyIM.sendMessageChatRoom( jidChatRoom, _textarea.value ) )
1143                        return false;
1144               
1145                _textarea.value = '';
1146               
1147                _textarea.focus( );
1148        };
1149       
1150        loadscript.configEvents( _send, 'onclick', _send_message );
1151        loadscript.configEvents( _leaveChatRoom, 'onclick', function( )
1152        {
1153                TrophyIM.leaveChatRoom( jidChatRoom );
1154
1155                setTimeout( function()
1156                {
1157                        _winBuild('window_chat_room_' + jidChatRoom, 'remove');
1158                       
1159                }, 500 );
1160               
1161        });
1162       
1163                loadscript.configEvents( _textarea, 'onkeyup', function( e )
1164                {
1165                        if ( e.keyCode == 13 )
1166                        {
1167                                _send_message( );
1168                        }
1169                });       
1170       
1171        var winChatRoom =
1172        {
1173                         id_window              : "window_chat_room_" + arguments[0],
1174                         barejid                : jidChatRoom,
1175                         width                  : 500,
1176                         height                 : 450,
1177                         top                    : TrophyIM.posWindow.top,
1178                         left                   : TrophyIM.posWindow.left,
1179                         draggable              : true,
1180                         visible                : "display",
1181                         resizable              : true,
1182                         zindex                 : loadscript.getZIndex(),
1183                         title                  : titleWindow,
1184                         closeAction    : "hidden",
1185                         content                : _content     
1186        }
1187       
1188        _win = _winBuild(winChatRoom);
1189       
1190        return ( _messages = _win.content( ).firstChild );
1191       
1192    },
1193   
1194        /** Function addContacts
1195         *
1196         *  Parameters:
1197         *              (string) jidFrom         
1198         *      (string) jidTo
1199         *              (string) name
1200         *              (string) group   
1201         */
1202       
1203        addContact : function( jidTo, name, group )
1204        {
1205                // Add Contact
1206        var _id = TrophyIM.connection.getUniqueId('add');
1207                var newContact = $iq({type: 'set', id: _id });
1208                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1209                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
1210                        newContact = newContact.c('group').t(group).tree();
1211
1212                TrophyIM.connection.send(newContact);
1213        },
1214
1215    /** Function: add
1216     *
1217     *  Parameters:
1218     *    (string) msg - the message to add
1219     *    (string) jid - the jid of chat box to add the message to.
1220     */
1221       
1222    addMessage : function( chatBox, jid, msg )
1223    {
1224        // Get Smiles
1225        msg.msg = loadscript.getSmiles( msg.msg );
1226 
1227        var messageDiv  = document.createElement("div");
1228                messageDiv.style.margin = "3px 0px 1em 3px";
1229        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
1230               
1231        chatBox.appendChild(messageDiv);
1232        chatBox.scrollTop = chatBox.scrollHeight;
1233    },
1234       
1235    /** Function : renameContact
1236     *
1237     *
1238     */
1239   
1240    renameContact : function( jid )
1241    {
1242        // Name
1243        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
1244
1245                if(( name = prompt(i18n.ASK_NEW_NAME_QUESTION + name + "!", name )))
1246                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1247                                name = "";
1248
1249                if( name == null || name == "")
1250                        name = "";
1251               
1252        var jidTo = jid
1253        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
1254        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1255       
1256        TrophyIM.addContact( jidTo, name, group );
1257       
1258        document.getElementById('itenContact_' + jid ).innerHTML = name;
1259    },
1260   
1261    /** Function : renameGroup
1262     *
1263     *
1264     */
1265
1266    renameGroup : function( jid )
1267    {
1268        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1269        var presence    = TrophyIM.rosterObj.roster[jid].presence;
1270       
1271                // Group
1272                if(( group = prompt( i18n.ASK_NEW_GROUP_QUESTION, group )))
1273                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1274                                group = "";
1275
1276                if( group == null || group == "")
1277                        group = "";
1278
1279        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
1280        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
1281                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
1282
1283                TrophyIM.rosterObj.removeContact( jid );
1284               
1285                TrophyIM.addContact( jidTo, name, group );
1286       
1287                document.getElementById("JabberIMRoster").innerHTML = "";
1288               
1289        TrophyIM.renderRoster();
1290       
1291        setTimeout(function()
1292        {
1293                for( var i in presence )
1294                {
1295                        if ( presence[ i ].constructor == Function )
1296                                continue;
1297                               
1298                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
1299                }
1300        },500);
1301    },
1302
1303    /** Function createChatRooms
1304     *
1305     *
1306     */
1307   
1308    createChatRooms : function()
1309    {
1310        var nickName     = document.getElementById('nickName_chatRoom_jabberit').value;
1311        var nameChatRoom = document.getElementById('name_ChatRoom_jabberit').value;
1312       
1313        var _from               = Base64.decode( loadscript.getUserCurrent().jid ) + TROPHYIM_RESOURCE;
1314                var _to                 = escape( nameChatRoom ) + "@" + TROPHYIM_CHATROOM + "/" + nickName ;
1315                var new_room    = $pres( {from: _from, to: _to } ).c( "x", { xmlns: Strophe.NS.MUC } );
1316
1317                TrophyIM.connection.send( new_room.tree() );
1318    },
1319   
1320    /** Function : joinRoom
1321     *
1322     *
1323     */
1324   
1325    joinChatRoom : function( roomName )
1326    {
1327        var presence = $pres( {from: TrophyIM.connection.jid, to: roomName} ).c("x",{xmlns: Strophe.NS.MUC});
1328       
1329                TrophyIM.connection.send( presence );
1330    },
1331   
1332    /** Function : Leave Chat Room
1333     *
1334     *
1335     */
1336   
1337    leaveChatRoom : function( roomName )
1338    {
1339        var room_nick   = roomName;
1340       
1341        var presenceid  = TrophyIM.connection.getUniqueId();
1342       
1343        var presence    = $pres( {type: "unavailable", id: presenceid, from: TrophyIM.connection.jid, to: room_nick} ).c("x",{xmlns: Strophe.NS.MUC});
1344       
1345        TrophyIM.connection.send( presence );       
1346    },
1347   
1348    /** Function : getlistRooms
1349     *
1350     *
1351     */
1352   
1353    getListRooms : function()
1354    {
1355        var _error_return = function(element)
1356        {
1357                alert( " ERROR : " + element );
1358        };
1359       
1360                var iq = $iq({to: "conference.im.pr.gov.br", type: "get"}).c("query",{xmlns: Strophe.NS.DISCO_ITEMS});                 
1361               
1362        TrophyIM.connection.sendIQ( iq, loadscript.listRooms, _error_return, 500 );             
1363    },
1364   
1365    /** Function: removeContact
1366     *
1367     *  Parameters:
1368     *          (string) jidTo
1369     */
1370   
1371    removeContact : function( jidTo )
1372    {
1373        var divItenContact       = null;
1374
1375        if( ( divItenContact = document.getElementById('itenContact_' + jidTo )))
1376        {       
1377                // Remove Contact
1378                var _id = TrophyIM.connection.getUniqueId();   
1379                var delContact  = $iq({type: 'set', id: _id})
1380                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1381                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
1382
1383                TrophyIM.connection.send( delContact );
1384               
1385                        loadscript.removeElement( document.getElementById('itenContactNotification_' + jidTo ) );
1386               
1387                var spanShow = document.getElementById('span_show_itenContact_' + jidTo )
1388                        spanShow.parentNode.removeChild(spanShow);
1389               
1390                loadscript.removeGroup( divItenContact.parentNode );
1391               
1392                divItenContact.parentNode.removeChild(divItenContact);
1393        }
1394    },
1395   
1396    /** Function: renderRoster
1397     *
1398     *  Renders roster, looking only for jids flagged by setPresence as having
1399     *  changed.
1400     */
1401   
1402        renderRoster : function()
1403        {
1404                var roster_div = document.getElementById('JabberIMRoster');
1405               
1406                if( roster_div )
1407                {
1408                        var users = new Array();
1409                       
1410                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1411                       
1412                        if( loading_gif.style.display == "block" )
1413                                loading_gif.style.display = "none";
1414                               
1415                        for( var user in TrophyIM.rosterObj.roster )
1416                        {
1417                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
1418                                        continue;
1419
1420                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
1421                        }
1422
1423                        users.sort();
1424                       
1425                        var groups              = new Array();
1426                        var flagGeral   = false;
1427                       
1428                        for (var group in TrophyIM.rosterObj.groups)
1429                        {
1430                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
1431                                        continue;
1432                               
1433                                if( group )
1434                                        groups[groups.length] = group;
1435                               
1436                                if( group == "Geral" )
1437                                        flagGeral = true;
1438            }
1439           
1440                        if( !flagGeral && users.length > 0 )
1441                                groups[groups.length] = "Geral";
1442                               
1443                        groups.sort();
1444                       
1445                        for ( var i = 0; i < groups.length; i++ )
1446                        {
1447                                TrophyIM.renderGroups( groups[i] , roster_div );       
1448                        }
1449                       
1450                        TrophyIM.renderItensGroup( users, roster_div );
1451                }
1452                       
1453                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
1454        },
1455       
1456    /** Function: renderGroups
1457     *
1458     *
1459     */
1460       
1461        renderGroups: function( nameGroup, element )
1462        {
1463                var _addGroup = function()
1464                {
1465                        var _nameGroup  = nameGroup;
1466                        var _element    = element;
1467
1468                        var paramsGroup =
1469                        {
1470                                'nameGroup'     : _nameGroup,
1471                                'path_jabberit' : path_jabberit
1472                        }
1473                       
1474                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
1475                }
1476
1477                if( !element.hasChildNodes() )
1478                {
1479                        _addGroup();
1480                }
1481                else
1482                {
1483                        var _NodeChild  = element.firstChild;
1484                        var flagAdd             = false;
1485                       
1486                        while( _NodeChild )
1487                        {
1488                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1489                                {
1490                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
1491                                        {
1492                                                flagAdd = true;
1493                                        }
1494                                }
1495                               
1496                                _NodeChild = _NodeChild.nextSibling;
1497                        }
1498
1499                        if( !flagAdd )
1500                        {
1501                                _addGroup();
1502                        }
1503                }
1504        },
1505
1506    /** Function: renderItensGroup
1507     *
1508     *
1509     */
1510
1511        renderItensGroup : function( users, element )
1512        {
1513                var addItem = function()
1514                {
1515                        if( arguments.length > 0 )
1516                        {
1517                                // Get Arguments
1518                                var objContact  = arguments[0];
1519                                var group               = arguments[1];
1520                                var element             = arguments[2];
1521                                var showOffline = loadscript.getShowContactsOffline();
1522                               
1523                                // Presence e Status
1524                                var presence            = "unavailable";
1525                                var status                      = "";
1526                                var statusColor         = "black";
1527                                var statusDisplay       = "none";
1528                               
1529                                var _resource   = "";
1530                               
1531                                // Set Presence
1532                                var _presence = function(objContact)
1533                                {
1534                                        if (objContact.presence)
1535                                        {
1536                                                for (var resource in objContact.presence)
1537                                                {
1538                                                        if ( objContact.presence[resource].constructor == Function )
1539                                                                continue;
1540
1541                                                        if( objContact.presence[resource].show != 'invisible' )
1542                                                                presence = objContact.presence[resource].show;
1543
1544                                                        if( objContact.contact.subscription != "both")
1545                                                                presence = 'subscription';
1546                                                       
1547                                                        if( objContact.presence[resource].status )
1548                                                        {
1549                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1550                                                                statusDisplay   = "block";
1551                                                        }
1552                                                }
1553                                        }
1554                                };
1555                               
1556                                // Set Subscription
1557                                var _subscription = function( objContact )
1558                                {
1559                                        if( objContact.contact.subscription != "both" )
1560                                        {
1561                                                switch( objContact.contact.subscription )
1562                                                {
1563                                                        case "none" :
1564                                                               
1565                                                                status          = " (( " + i18n.ASK_FOR_AUTH  + " )) ";
1566                                                                statusColor     = "red";
1567                                                                break;
1568       
1569                                                        case "to" :
1570                                                               
1571                                                                status          = " (( " + i18n.CONTACT_ASK_FOR_AUTH  + " )) ";
1572                                                                statusColor     = "orange";
1573                                                                break;
1574       
1575                                                        case "from" :
1576                                                               
1577                                                                status          = " (( " + i18n.AUTHORIZED + " )) ";
1578                                                                statusColor = "green";
1579                                                                break;
1580                                                               
1581                                                        case "subscribe" :
1582                                                               
1583                                                                status          = " (( " + i18n.AUTH_SENT  + " )) ";
1584                                                                statusColor     = "red";       
1585                                                                break;
1586
1587                                                        case "not-in-roster" :
1588                                                               
1589                                                                status          = " (( " + i18n.ASK_FOR_AUTH_QUESTION  + " )) ";
1590                                                                statusColor     = "orange";     
1591                                                                break;
1592                                                               
1593                                                        default :
1594                                                               
1595                                                                break;
1596                                                }
1597
1598                                                statusDisplay = "block";
1599                                        }
1600                                };
1601
1602                                if( objContact.contact.subscription != "remove")
1603                                {
1604                                        var itensJid    = document.getElementById( "itenContact_" + objContact.contact.jid );
1605                                       
1606                                        if( itensJid == null )
1607                                        {
1608                                                // Name
1609                                                var nameContact = "";                                   
1610                                               
1611                                                if ( objContact.contact.name )
1612                                                        nameContact = objContact.contact.name;
1613                                                else
1614                                                {
1615                                                        nameContact = objContact.contact.jid;
1616                                                        nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1617                                                }
1618                                               
1619                                                // Get Presence
1620                                                _presence(objContact);
1621                                               
1622                                                var paramsContact =
1623                                                {
1624                                                        divDisplay              : "block",
1625                                                        id                              : 'itenContact_' + objContact.contact.jid ,
1626                                                        jid                             : objContact.contact.jid,
1627                                                        nameContact     : nameContact,
1628                                                        path_jabberit   : path_jabberit,
1629                                                        presence                : presence,
1630                                                        spanDisplay             : statusDisplay,
1631                                                        status                  : status,
1632                                                        statusColor             : "black",
1633                                                        subscription    : objContact.contact.subscription,
1634                                                        resource                : _resource
1635                                                }
1636                                               
1637                                                // Get Authorization
1638                                                _subscription( objContact );
1639                                               
1640                                                if( group != "")
1641                                                {
1642                                                        var _NodeChild          = element.firstChild;
1643                                                       
1644                                                        while( _NodeChild )
1645                                                        {
1646                                                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1647                                                                {
1648                                                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1649                                                                        {
1650                                                                                _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1651                                                                        }
1652                                                                }
1653       
1654                                                                _NodeChild = _NodeChild.nextSibling;
1655                                                        }
1656                                                }       
1657                                        }
1658                                        else
1659                                        {
1660                                                // Get Presence
1661                                                _presence(objContact);
1662       
1663                                                var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1664                                                        is_open = is_open.indexOf("arrow_down.gif");
1665       
1666                                                // Get Authorization
1667                                                _subscription( objContact );
1668                                               
1669                                                // Set subscription
1670                                                itensJid.setAttribute('subscription', objContact.contact.subscription );
1671                                               
1672                                                with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ) )
1673                                                {
1674                                                        if( presence == "unavailable" && !showOffline )
1675                                                        {
1676                                                                style.display = "none";
1677                                                        }
1678                                                        else
1679                                                        {
1680                                                                if( is_open > 0 )
1681                                                                {
1682                                                                        style.display   = statusDisplay;
1683                                                                        style.color             = statusColor;
1684                                                                        innerHTML               = status;
1685                                                                }
1686                                                        }
1687                                                }
1688                                               
1689                                                if( presence == "unavailable" && !showOffline )
1690                                                {
1691                                                        itensJid.style.display = "none";
1692                                                }
1693                                                else
1694                                                {
1695                                                        if( is_open > 0 )
1696                                                        {
1697                                                                itensJid.style.display = "block";
1698                                                        }
1699                                                }
1700                                               
1701                                                itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1702                                        }
1703       
1704                                        // Contact OffLine
1705                                        if( !objContact.presence && !showOffline )
1706                                        {
1707                                                if( objContact.contact.subscription != "remove" )
1708                                                {
1709                                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ))
1710                                                        {
1711                                                                style.display   = "none";
1712                                                        }
1713               
1714                                                        with ( document.getElementById('itenContact_' + objContact.contact.jid ) )
1715                                                        {
1716                                                                style.display   = "none";
1717                                                        }
1718                                                }
1719                                        }
1720                                }
1721                        }
1722                };
1723               
1724                var flag = false;
1725               
1726                for( var i = 0 ; i < users.length; i++ )
1727                {
1728                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode( loadscript.getUserCurrent().jid) )
1729                        {
1730                                var _subscription = TrophyIM.rosterObj.roster[users[i]].contact.subscription;
1731                               
1732                                if( _subscription === "to" )
1733                                {
1734                                        flag = true;
1735                                }
1736                               
1737                                if(  _subscription === "not-in-roster")
1738                                {
1739                                        flag = true;
1740                                }
1741                               
1742                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1743                                {
1744                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1745                                       
1746                                        if( groups.length > 0 )
1747                                        {
1748                                                for( var j = 0; j < groups.length; j++ )
1749                                                {
1750                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element );
1751                                                }
1752                                        }
1753                                        else
1754                                        {
1755                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1756                                        }
1757                                }
1758                                else
1759                                {
1760                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1761                                }
1762                        }
1763                }
1764               
1765                if( flag )
1766                {
1767                        if ( TrophyIM.controll.notificationNewUsers == 0 )
1768                        {
1769                                loadscript.enabledNotificationNewUsers();
1770                                TrophyIM.controll.notificationNewUsers++;
1771                        }
1772                }
1773                else
1774                {
1775                        loadscript.disabledNotificationNewUsers();
1776                        TrophyIM.controll.notificationNewUsers = 0;
1777                }
1778        },
1779
1780    /** Function: rosterClick
1781     *
1782     *  Handles actions when a roster item is clicked
1783     */
1784   
1785        rosterClick : function(fulljid)
1786        {
1787        TrophyIM.makeChat(fulljid);
1788    },
1789
1790        /** Function SetAutorization
1791         *
1792         */
1793
1794        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1795        {
1796        var _id = TrophyIM.connection.getUniqueId();
1797       
1798        TrophyIM.connection.send($pres( ).attrs({ from: jidFrom, to: jidTo, type: _typeSubscription, id: _id }).tree());
1799        },
1800
1801        /** Function: setPresence
1802     *
1803     */
1804
1805        setPresence : function( _type )
1806        {
1807                if( _type != 'status')
1808                {
1809                        if( _type == "unavailable" &&  TrophyIM.statusConn.connected )
1810                        {
1811                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1812                               
1813                                if( TrophyIM._timeOut.renderRoster != null )
1814                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1815                               
1816                                if( TrophyIM.statusConn.connected )
1817                                        TrophyIM.connection.send($pres({type : _type}).tree());
1818                               
1819                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1820                        {
1821                                if( TrophyIM.connection._requests[i] )
1822                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1823                        }
1824                               
1825                                TrophyIM.logout();
1826                               
1827                        loadscript.clrAllContacts();
1828                       
1829                        delete TrophyIM.rosterObj.roster;
1830                        delete TrophyIM.rosterObj.groups;
1831                       
1832                        setTimeout(function()
1833                        {
1834                                        if( loading_gif.style.display == "block" )
1835                                                loading_gif.style.display = "none";
1836                        }, 1000);
1837                        }
1838                        else
1839                        {
1840                                if( !TrophyIM.autoConnection.connect )
1841                                {
1842                                        TrophyIM.autoConnection.connect = true;
1843                                        TrophyIM.load();
1844                                }
1845                                else
1846                                {
1847                                        if( TrophyIM.statusConn.connected )
1848                                        {
1849                                                if( loadscript.getStatusMessage() != "" )
1850                                                {
1851                                                        var _presence = $pres( );
1852                                                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1853                                                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1854                                                       
1855                                                        TrophyIM.connection.send( _presence.tree() );
1856                                                }
1857                                                else
1858                                                {
1859                                                        TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1860                                                }
1861                                        }
1862                                }
1863                        }
1864                }
1865                else
1866                {
1867                        var _show       = "available";
1868                        var _status     = "";
1869                       
1870                        if( arguments.length < 2 )
1871                        {
1872                                if( loadscript.getStatusMessage() != "" )
1873                                        _status = prompt(i18n.TYPE_YOUR_MSG, loadscript.getStatusMessage());
1874                                else
1875                                        _status = prompt(i18n.TYPE_YOUR_MSG);
1876                               
1877                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1878                               
1879                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1880                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1881                        }
1882                        else
1883                        {
1884                                _status = arguments[1];
1885                        }
1886
1887                        for( var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1888                        {
1889                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1890                                continue;
1891                       
1892                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1893                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1894                        }
1895
1896                        if ( TrophyIM.statusConn.connected )
1897                        {
1898                                var _presence = $pres( );
1899                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1900                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1901                               
1902                                TrophyIM.connection.send( _presence.tree() );
1903                        }
1904                }
1905        },
1906       
1907        /** Function: sendMessage
1908     *
1909     *  Send message from chat input to user
1910     */
1911     
1912    sendMessage : function()
1913    {
1914                if (arguments.length > 0)
1915                {
1916                        var jidTo = arguments[0];
1917                        var message_input = arguments[1];
1918                       
1919                       
1920                        message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g, "");
1921                       
1922                        if (message_input != "") {
1923                       
1924                                // Send Message
1925                                var newMessage = $msg({
1926                                        to: jidTo,
1927                                        from: TrophyIM.connection.jid,
1928                                        type: 'chat'
1929                                });
1930                                newMessage = newMessage.c('body').t(message_input);
1931                                newMessage.up();
1932                                newMessage = newMessage.c('active').attrs({
1933                                        xmlns: 'http://jabber.org/protocol/chatstates'
1934                                });
1935                                // Send Message
1936                                TrophyIM.connection.send(newMessage.tree());
1937                               
1938                                return true;
1939                        }
1940                }
1941               
1942                return false;
1943    },
1944
1945        /** Function: sendMessage
1946    *
1947    *  Send message to ChatRoom
1948    */
1949   
1950    sendMessageChatRoom : function( room )
1951    {
1952        if( arguments.length > 0 )
1953        {
1954                var room_nick   = arguments[0];
1955                var message             = arguments[1];
1956                var msgid               = TrophyIM.connection.getUniqueId();
1957                var msg                 = $msg({to: room_nick, type: "groupchat", id: msgid}).c("body",{xmlns: Strophe.NS.CLIENT}).t(message);
1958               
1959                msg.up();//.c("x", {xmlns: "jabber:x:event"}).c("composing");
1960               
1961                TrophyIM.connection.send(msg);
1962               
1963                return true;
1964        }
1965    },
1966   
1967        /** Function: sendContentMessage
1968     *
1969     *  Send a content message from chat input to user
1970     */
1971        sendContentMessage : function()
1972    {
1973      if( arguments.length > 0 )
1974      {
1975         var jidTo = arguments[0];
1976         var state = arguments[1];
1977
1978         var newMessage = $msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'});
1979         newMessage = newMessage.c(state).attrs({xmlns : 'http://jabber.org/protocol/chatstates'});
1980         // Send content message
1981         TrophyIM.connection.send(newMessage.tree());
1982      }
1983    }
1984};
1985
1986/** Class: TrophyIMRoster
1987 *
1988 *
1989 *  This object stores the roster and presence info for the TrophyIMClient
1990 *
1991 *  roster[jid_lower]['contact']
1992 *  roster[jid_lower]['presence'][resource]
1993 */
1994function TrophyIMRoster()
1995{
1996    /** Constants: internal arrays
1997     *    (Object) roster - the actual roster/presence information
1998     *    (Object) groups - list of current groups in the roster
1999     *    (Array) changes - array of jids with presence changes
2000     */
2001    if (TrophyIM.JSONStore.store_working)
2002        {
2003        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
2004        this.roster = (data['roster'] != null) ? data['roster'] : {};
2005        this.groups = (data['groups'] != null) ? data['groups'] : {};
2006    }
2007        else
2008        {
2009        this.roster = {};
2010        this.groups = {};
2011    }
2012    this.changes = new Array();
2013   
2014        if (TrophyIM.constants.stale_roster)
2015        {
2016        for (var jid in this.roster)
2017                {
2018                        this.changes[this.changes.length] = jid;
2019        }
2020    }
2021
2022        /** Function: addChange
2023         *
2024         *  Adds given jid to this.changes, keeping this.changes sorted and
2025         *  preventing duplicates.
2026         *
2027         *  Parameters
2028         *    (String) jid : jid to add to this.changes
2029         */
2030         
2031        this.addChange = function(jid)
2032        {
2033                for (var c = 0; c < this.changes.length; c++)
2034                {
2035                        if (this.changes[c] == jid)
2036                        {
2037                                return;
2038                        }
2039                }
2040               
2041                this.changes[this.changes.length] = jid;
2042               
2043                this.changes.sort();
2044        }
2045       
2046    /** Function: addContact
2047     *
2048     *  Adds given contact to roster
2049     *
2050     *  Parameters:
2051     *    (String) jid - bare jid
2052     *    (String) subscription - subscription attribute for contact
2053     *    (String) name - name attribute for contact
2054     *    (Array)  groups - array of groups contact is member of
2055     */
2056   
2057        this.addContact = function(jid, subscription, name, groups )
2058        {
2059                if( subscription === "remove" )
2060        {
2061                        this.removeContact(jid);
2062        }
2063        else
2064        {
2065                        var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
2066                var jid_lower   = jid.toLowerCase();
2067       
2068                        if ( this.roster[jid_lower] )
2069                        {
2070                    this.roster[jid_lower]['contact'] = contact;
2071                }
2072                        else
2073                        {
2074                    this.roster[jid_lower] = {contact:contact};
2075                }
2076
2077                        groups = groups ? groups : [''];
2078               
2079                        for ( var g = 0; g < groups.length; g++ )
2080                        {
2081                                if ( !this.groups[groups[g]] )
2082                                {
2083                        this.groups[groups[g]] = {};
2084                    }
2085                   
2086                                this.groups[groups[g]][jid_lower] = jid_lower;
2087                }
2088        }
2089    }
2090   
2091    /** Function: getContact
2092     *
2093     *  Returns contact entry for given jid
2094     *
2095     *  Parameter: (String) jid - jid to return
2096     */
2097     
2098    this.getContact = function(jid)
2099        {
2100        if (this.roster[jid.toLowerCase()])
2101                {
2102            return this.roster[jid.toLowerCase()]['contact'];
2103        }
2104    }
2105
2106   /** Function: getPresence
2107        *
2108        *  Returns best presence for given jid as Array(resource, priority, show,
2109        *  status)
2110        *
2111        *  Parameter: (String) fulljid - jid to return best presence for
2112        */
2113         
2114        this.getPresence = function(fulljid)
2115        {
2116                var jid = Strophe.getBareJidFromJid(fulljid);
2117                var current = null;
2118                   
2119                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
2120                {
2121                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
2122                        {
2123                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
2124                                continue;
2125                       
2126                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
2127                                if (current == null)
2128                                {
2129                                        current = presence
2130                                }
2131                                else
2132                                {
2133                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
2134                                        || presence['show'] == "available") || (current['show'] != "chat" ||
2135                                        current['show'] != "available")))
2136                                        {
2137                                                current = presence
2138                                        }
2139                                }
2140                        }
2141                }
2142                return current;
2143        }
2144
2145        /** Function: groupHasChanges
2146         *
2147         *  Returns true if current group has members in this.changes
2148         *
2149         *  Parameters:
2150         *    (String) group - name of group to check
2151         */
2152         
2153        this.groupHasChanges = function(group)
2154        {
2155                for (var c = 0; c < this.changes.length; c++)
2156                {
2157                        if (this.groups[group][this.changes[c]])
2158                        {
2159                                return true;
2160                        }
2161                }
2162                return false;
2163        }
2164       
2165        /** Function removeContact
2166         *
2167         * Parameters
2168         *       (String) jid           
2169         */
2170         
2171         this.removeContact = function(jid)
2172         {
2173                if( this.roster[ jid ] )
2174                {
2175                        var groups = this.roster[ jid ].contact.groups;
2176                       
2177                        if( groups )
2178                        {
2179                                for ( var i = 0; i < groups.length; i++ )
2180                                {
2181                                        delete this.groups[ groups[ i ] ][ jid ];
2182                                }
2183       
2184                                for ( var i = 0; i < groups.length; i++ )
2185                                {
2186                                        var contacts = 0;
2187                                        for ( var contact in this.groups[ groups[ i ] ] )
2188                                        {
2189                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
2190                                                continue;
2191                                       
2192                                                contacts++;
2193                                        }
2194               
2195                                        if ( ! contacts )
2196                                                delete this.groups[ groups[ i ] ];
2197                                }
2198                        }
2199       
2200                        // Delete Object roster
2201                        if( this.roster[jid] )
2202                                delete this.roster[jid];
2203                }
2204         }
2205         
2206    /** Function: setPresence
2207     *
2208     *  Sets presence
2209     *
2210     *  Parameters:
2211     *    (String) fulljid: full jid with presence
2212     *    (Integer) priority: priority attribute from presence
2213     *    (String) show: show attribute from presence
2214     *    (String) status: status attribute from presence
2215     */
2216   
2217        this.setPresence = function(fulljid, priority, show, status)
2218        {
2219                var barejid             = Strophe.getBareJidFromJid(fulljid);
2220        var resource    = Strophe.getResourceFromJid(fulljid);
2221        var jid_lower   = barejid.toLowerCase();
2222       
2223        if( show != 'unavailable' || show != 'error' )
2224                {
2225            if (!this.roster[jid_lower])
2226                        {
2227                this.addContact( barejid, 'not-in-roster' );
2228            }
2229           
2230            var presence =
2231                        {
2232                resource        : resource,
2233                priority        : priority,
2234                show            : show,
2235                status          : status
2236            }
2237           
2238                        if (!this.roster[jid_lower]['presence'])
2239                        {
2240                this.roster[jid_lower]['presence'] = {};
2241            }
2242           
2243            this.roster[jid_lower]['presence'][resource] = presence;   
2244                }
2245    }
2246
2247        /** Fuction: save
2248         *
2249         *  Saves roster data to JSON store
2250         */
2251       
2252        this.save = function()
2253        {
2254                if (TrophyIM.JSONStore.store_working)
2255                {
2256                        TrophyIM.JSONStore.setData({roster:this.roster,
2257                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
2258                        chat_history:TrophyIM.chatHistory});
2259                }
2260        }
2261
2262}
2263/** Class: TrophyIMJSONStore
2264 *
2265 *
2266 *  This object is the mechanism by which TrophyIM stores and retrieves its
2267 *  variables from the url provided by TROPHYIM_JSON_STORE
2268 *
2269 */
2270function TrophyIMJSONStore() {
2271    this.store_working = false;
2272    /** Function _newXHR
2273     *
2274     *  Set up new cross-browser xmlhttprequest object
2275     *
2276     *  Parameters:
2277     *    (function) handler = what to set onreadystatechange to
2278     */
2279     this._newXHR = function (handler) {
2280        var xhr = null;
2281        if (window.XMLHttpRequest) {
2282            xhr = new XMLHttpRequest();
2283            if (xhr.overrideMimeType) {
2284            xhr.overrideMimeType("text/xml");
2285            }
2286        } else if (window.ActiveXObject) {
2287            xhr = new ActiveXObject("Microsoft.XMLHTTP");
2288        }
2289        return xhr;
2290    }
2291    /** Function getData
2292     *  Gets data from JSONStore
2293     *
2294     *  Parameters:
2295     *    (Array) vars = Variables to get from JSON store
2296     *
2297     *  Returns:
2298     *    Object with variables indexed by names given in parameter 'vars'
2299     */
2300    this.getData = function(vars) {
2301        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2302            Strophe.debug("Retrieving JSONStore data");
2303            var xhr = this._newXHR();
2304            var getdata = "get=" + vars.join(",");
2305            try {
2306                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2307            } catch (e) {
2308                Strophe.error("JSONStore open failed.");
2309                return false;
2310            }
2311            xhr.setRequestHeader('Content-type',
2312            'application/x-www-form-urlencoded');
2313            xhr.setRequestHeader('Content-length', getdata.length);
2314            xhr.send(getdata);
2315            if (xhr.readyState == 4 && xhr.status == 200) {
2316                try {
2317                    var dataObj = JSON.parse(xhr.responseText);
2318                    return this.emptyFix(dataObj);
2319                } catch(e) {
2320                    Strophe.error("Could not parse JSONStore response" +
2321                    xhr.responseText);
2322                    return false;
2323                }
2324            } else {
2325                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2326                return false;
2327            }
2328        }
2329    }
2330    /** Function emptyFix
2331     *    Fix for bugs in external JSON implementations such as
2332     *    http://bugs.php.net/bug.php?id=41504.
2333     *    A.K.A. Don't use PHP, people.
2334     */
2335    this.emptyFix = function(obj) {
2336        if (typeof(obj) == "object") {
2337            for (var i in obj) {
2338                        if ( obj[i].constructor == Function )
2339                                continue;
2340                       
2341                if (i == '_empty_') {
2342                    obj[""] = this.emptyFix(obj['_empty_']);
2343                    delete obj['_empty_'];
2344                } else {
2345                    obj[i] = this.emptyFix(obj[i]);
2346                }
2347            }
2348        }
2349        return obj
2350    }
2351    /** Function delData
2352     *    Deletes data from JSONStore
2353     *
2354     *  Parameters:
2355     *    (Array) vars  = Variables to delete from JSON store
2356     *
2357     *  Returns:
2358     *    Status of delete attempt.
2359     */
2360    this.delData = function(vars) {
2361        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2362            Strophe.debug("Retrieving JSONStore data");
2363            var xhr = this._newXHR();
2364            var deldata = "del=" + vars.join(",");
2365            try {
2366                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2367            } catch (e) {
2368                Strophe.error("JSONStore open failed.");
2369                return false;
2370            }
2371            xhr.setRequestHeader('Content-type',
2372            'application/x-www-form-urlencoded');
2373            xhr.setRequestHeader('Content-length', deldata.length);
2374            xhr.send(deldata);
2375            if (xhr.readyState == 4 && xhr.status == 200) {
2376                try {
2377                    var dataObj = JSON.parse(xhr.responseText);
2378                    return dataObj;
2379                } catch(e) {
2380                    Strophe.error("Could not parse JSONStore response");
2381                    return false;
2382                }
2383            } else {
2384                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2385                return false;
2386            }
2387        }
2388    }
2389    /** Function setData
2390     *    Stores data in JSONStore, overwriting values if they exist
2391     *
2392     *  Parameters:
2393     *    (Object) vars : Object containing named vars to store ({name: value,
2394     *    othername: othervalue})
2395     *
2396     *  Returns:
2397     *    Status of storage attempt
2398     */
2399    this.setData = function(vars)
2400    {
2401        if ( typeof(TROPHYIM_JSON_STORE) != undefined )
2402        {
2403            var senddata = "set=" + JSON.stringify(vars);
2404            var xhr = this._newXHR();
2405            try
2406            {
2407                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2408            }
2409            catch (e)
2410            {
2411                Strophe.error("JSONStore open failed.");
2412                return false;
2413            }
2414            xhr.setRequestHeader('Content-type',
2415            'application/x-www-form-urlencoded');
2416            xhr.setRequestHeader('Content-length', senddata.length);
2417            xhr.send(senddata);
2418            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
2419            "OK") {
2420                return true;
2421            } else {
2422                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2423                return false;
2424            }
2425        }
2426    }
2427   
2428    var testData = true;
2429   
2430    if (this.setData({testData:testData})) {
2431        var testResult = this.getData(['testData']);
2432        if (testResult && testResult['testData'] == true) {
2433            this.store_working = true;
2434        }
2435    }
2436}
2437/** Constants: Node types
2438 *
2439 * Implementations of constants that IE doesn't have, but we need.
2440 */
2441if (document.ELEMENT_NODE == null) {
2442    document.ELEMENT_NODE = 1;
2443    document.ATTRIBUTE_NODE = 2;
2444    document.TEXT_NODE = 3;
2445    document.CDATA_SECTION_NODE = 4;
2446    document.ENTITY_REFERENCE_NODE = 5;
2447    document.ENTITY_NODE = 6;
2448    document.PROCESSING_INSTRUCTION_NODE = 7;
2449    document.COMMENT_NODE = 8;
2450    document.DOCUMENT_NODE = 9;
2451    document.DOCUMENT_TYPE_NODE = 10;
2452    document.DOCUMENT_FRAGMENT_NODE = 11;
2453    document.NOTATION_NODE = 12;
2454}
2455
2456/** Function: importNode
2457 *
2458 *  document.importNode implementation for IE, which doesn't have importNode
2459 *
2460 *  Parameters:
2461 *    (Object) node - dom object
2462 *    (Boolean) allChildren - import node's children too
2463 */
2464if (!document.importNode) {
2465    document.importNode = function(node, allChildren) {
2466        switch (node.nodeType) {
2467            case document.ELEMENT_NODE:
2468                var newNode = document.createElement(node.nodeName);
2469                if (node.attributes && node.attributes.length > 0) {
2470                    for(var i = 0; i < node.attributes.length; i++) {
2471                        newNode.setAttribute(node.attributes[i].nodeName,
2472                        node.getAttribute(node.attributes[i].nodeName));
2473                    }
2474                }
2475                if (allChildren && node.childNodes &&
2476                node.childNodes.length > 0) {
2477                    for (var i = 0; i < node.childNodes.length; i++) {
2478                        newNode.appendChild(document.importNode(
2479                        node.childNodes[i], allChildren));
2480                    }
2481                }
2482                return newNode;
2483                break;
2484            case document.TEXT_NODE:
2485            case document.CDATA_SECTION_NODE:
2486            case document.COMMENT_NODE:
2487                return document.createTextNode(node.nodeValue);
2488                break;
2489        }
2490    };
2491}
2492
2493/**
2494 *
2495 * Bootstrap self into window.onload and window.onunload
2496 */
2497
2498var oldonunload = window.onunload;
2499
2500window.onunload = function()
2501{
2502        if( oldonunload )
2503        {
2504        oldonunload();
2505    }
2506       
2507        TrophyIM.setPresence('unavailable');
2508}
Note: See TracBrowser for help on using the repository browser.