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

Revision 3116, 71.1 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                        // Get Jid/From = idElement
687                        var _idElement = ( xquery[i].firstChild.getAttribute('jid') != null ) ? xquery[i].firstChild.getAttribute('jid') : xquery[i].parentNode.getAttribute('from') ;
688                                _idElement = nameChatRoom + "_UserChatRoom__" + _idElement;
689                         
690                        var _UserChatRoom = document.createElement("div");
691                                _UserChatRoom.id = _idElement;
692                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");
693                                _UserChatRoom.appendChild( document.createTextNode(nickName) );
694
695                        var nodeUser = document.getElementById( _idElement );           
696                       
697                        if( nodeUser == null && xquery[i].firstChild.getAttribute('jid') )
698                        {
699                                if( document.getElementById( nameChatRoom + '__roomChat__participants' ) != null )
700                                {
701                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
702                                        nameChatRoom.appendChild( _UserChatRoom );
703                                }
704                                else
705                                {
706                                        TrophyIM.makeChatRoom( nameChatRoom, nameChatRoom.substring(0, nameChatRoom.indexOf('@')) );
707                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
708                                        nameChatRoom.appendChild( _UserChatRoom );
709                                }
710                        }
711                        else
712                        {
713                                if( type == 'unavailable' )
714                                {
715                                        var nodeUser = "";
716                                       
717                                        if( xquery[i].firstChild.getAttribute('jid') != null )
718                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') );
719                                        else
720                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].parentNode.getAttribute('to') );
721                                       
722                                        nodeUser.parentNode.removeChild( nodeUser );
723                                }
724                                else if( show )
725                                {
726                                        var _UserChatRoom = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') )
727                                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");   
728                                }
729                        }
730                }
731               
732                /*if( xmlns.indexOf("http://jabber.org/protocol/muc#user") == 0 )
733                {
734                        var nameChatRoom = xquery[i].parentNode.getAttribute('from');
735                                nameChatRoom = Strophe.getBareJidFromJid(nameChatRoom);
736
737                        var nickName = xquery[i].parentNode.getAttribute('from');
738                                nickName = Strophe.getResourceFromJid(nickName);
739
740                        var type = ( xquery[i].parentNode.getAttribute('type') != null ) ? xquery[i].parentNode.getAttribute('type') : 'available' ;
741                       
742                        var show = ( xquery[i].parentNode.firstChild.firstChild.nodeName.toLowerCase() == "show" ) ? xquery[i].parentNode.firstChild.firstChild.nodeValue : type ;
743                       
744                        if( xquery[i].firstChild.getAttribute('jid') )
745                        {
746                                if ( Strophe.getBareJidFromJid( xquery[i].firstChild.getAttribute('jid') ) == Strophe.getBareJidFromJid( TrophyIM.connection.jid ) )
747                                        show = loadscript.getStatusUserIM();
748                        }
749                       
750                        var _UserChatRoom = document.createElement("div");
751                                _UserChatRoom.id = nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid');
752                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");
753                                _UserChatRoom.appendChild( document.createTextNode(nickName) );
754               
755                        var nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') );         
756                               
757                        if( nodeUser == null && xquery[i].firstChild.getAttribute('jid') )
758                        {
759                                if( document.getElementById( nameChatRoom + '__roomChat__participants' ) != null )
760                                {
761                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
762                                        nameChatRoom.appendChild( _UserChatRoom );
763                                }
764                                else
765                                {
766                                        TrophyIM.makeChatRoom( nameChatRoom, nameChatRoom );
767                                        nameChatRoom = document.getElementById( nameChatRoom + '__roomChat__participants' );
768                                        nameChatRoom.appendChild( _UserChatRoom );
769                                }
770                        }
771                        else
772                        {
773                                if( type == 'unavailable' )
774                                {
775                                        var nodeUser = "";
776                                       
777                                        if( xquery[i].firstChild.getAttribute('jid') != null )
778                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') );
779                                        else
780                                                nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].parentNode.getAttribute('to') );
781                                       
782                                        nodeUser.parentNode.removeChild( nodeUser );
783                                }
784                                else if( show )
785                                {
786                                        var _UserChatRoom = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') )
787                                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");   
788                                }
789                        }
790                }*/
791            }
792        }
793    },   
794   
795    /** Function: onMessage
796     *
797     *  Message handler
798     */
799   
800    onMessage : function(msg)
801    {
802        var checkTime = function(i)
803        {
804                if ( i < 10 ) i= "0" + i;
805               
806                return i;
807        };
808       
809                var messageDate = function( _date )
810                {
811                        var _dt = _date.substr( 0, _date.indexOf( 'T' ) ).split( '-' );
812                        var _hr = _date.substr( _date.indexOf( 'T' ) + 1, _date.length - _date.indexOf( 'T' ) - 2 ).split( ':' );
813                       
814                        ( _date = new Date ).setTime( Date.UTC( _dt[0], _dt[1] - 1, _dt[2], _hr[0], _hr[1], _hr[2] ) );
815
816                        return ( _date.toLocaleDateString( ).replace( /-/g, '/' ) + ' ' + _date.toLocaleTimeString( ) );
817                };
818
819        var data        = new Date();
820        var dtNow       = checkTime(data.getHours()) + ":" + checkTime(data.getMinutes()) + ":" + checkTime(data.getSeconds());
821       
822        var from        = msg.getAttribute('from');
823        var type        = msg.getAttribute('type');
824        var elems       = msg.getElementsByTagName('body');
825        var delay       = ( msg.getElementsByTagName('delay') ) ? msg.getElementsByTagName('delay') : null;
826        var stamp       = ( delay[0] != null ) ? "<font style='color:red;'>" + messageDate(delay[0].getAttribute('stamp')) + "</font>" :  dtNow;
827
828                var barejid             = Strophe.getBareJidFromJid(from);
829                var jidChatRoom = Strophe.getResourceFromJid(from);
830                var jid_lower   = barejid.toLowerCase();
831                var contact             = "";
832                var state               = "";
833
834                var chatBox     = document.getElementById(jid_lower + "__chatState");
835                var chatStateOnOff = null;
836                var active      = msg.getElementsByTagName('active');
837               
838                contact = barejid.toLowerCase();
839                contact = contact.substring(0, contact.indexOf('@'));
840           
841                if( TrophyIM.rosterObj.roster[barejid] )
842                {
843                        if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
844                        {
845                                contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
846                        }
847                }
848
849                // Message with body are "content message", this means state active
850                if ( elems.length > 0 )
851                {
852                        state = "";
853                       
854                        // Set notify chat state capability on when sender notify it themself
855                        chatStateOnOff = document.getElementById(jid_lower + "__chatStateOnOff");
856                       
857                        if (active.length > 0 & chatStateOnOff != null )
858                        {
859                                chatStateOnOff.value = 'on';
860                        }
861
862                        // Get Message
863                        var _message = document.createElement("div");
864                        _message.innerHTML = Strophe.getText(elems[0]);
865                       
866                        var scripts = _message.getElementsByTagName('script');
867                       
868                        for (var i = 0; i < scripts.length; i++)
869                                _message.removeChild(scripts[i--]);
870                       
871                        _message.innerHTML = _message.innerHTML.replace(/^\s+|\s+$|^\n|\n$/g, "");
872                       
873                        // Get Smiles
874                        _message.innerHTML = loadscript.getSmiles( _message.innerHTML );
875
876                        if (type == 'chat' || type == 'normal')
877                        {
878                                if ( _message.hasChildNodes() )
879                                {
880                                        var message =
881                                        {
882                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + contact + "</font>",
883                                msg             : "</br>" + _message.innerHTML
884                        };
885                                       
886                                        TrophyIM.addMessage( TrophyIM.makeChat( from ), jid_lower, message );
887                                }
888                        }
889                        else if( type == 'groupchat')
890                        {
891                                if ( _message.hasChildNodes() )
892                                {
893                                        var message =
894                                        {
895                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + jidChatRoom + "</font>",
896                                msg             : "</br>" + _message.innerHTML
897                        };
898
899                                        TrophyIM.addMessage( TrophyIM.makeChatRoom( barejid ), jid_lower, message );
900                                }
901                        }
902                }
903                // Message without body are "content message", this mean state is not active
904                else
905                {
906                        if( chatBox != null )
907                                state = TrophyIM.getChatState(msg);                     
908                }
909               
910                // Clean chat status message some time later           
911                var clearChatState = function()
912                {
913                        chatBox.innerHTML='';
914                }
915               
916                if (chatBox != null)
917                {
918                        var clearChatStateTimer;
919                       
920                        chatBox.innerHTML = "<font style='font-weight:bold; color:grey; float:right;'>" + state + "</font>";
921                       
922                        var _composing =  msg.getElementsByTagName('composing');
923                       
924                        if ( _composing.length == 0 )
925                               
926                                clearChatStateTimer = setTimeout(clearChatState, 2000);
927                        else
928                                clearTimeout(clearChatStateTimer);                     
929                }
930
931                return true;
932        },
933
934        /** Function: getChatState
935         *
936         *  Parameters:
937         *    (string) msg - the message to get chat state
938         *    (string) jid - the jid of chat box to update the chat state to.
939         */
940        getChatState : function(msg)
941        {
942                var     state =  msg.getElementsByTagName('inactive');
943               
944                if ( state.length > 0 )
945                {
946                return i18n.INACTIVE;
947                }
948                else
949                {
950                state = msg.getElementsByTagName('gone');
951            if ( state.length > 0 )
952            {
953                return i18n.GONE;
954                        }
955            else
956            {
957                state = msg.getElementsByTagName('composing');
958                if ( state.length > 0 )
959                {
960                        return i18n.COMPOSING;
961                                }
962                else
963                {
964                        state =  msg.getElementsByTagName('paused');
965                        if ( state.length > 0 )
966                        {
967                                return i18n.PAUSED;
968                                        }
969                                }
970                        }
971                }
972               
973                return '';
974        },
975
976        /** Function: makeChat
977     *
978     *  Make sure chat window to given fulljid exists, switching chat context to
979     *  given resource.
980     */
981     
982    makeChat : function(fulljid)
983    {
984        var barejid             = Strophe.getBareJidFromJid(fulljid);
985        var titleWindow = "";
986
987        var paramsChatBox =
988        {
989                        'enabledPopUp'  : ( ( loadscript.getIsIE() ) ? "none" : "block" ),
990                        'idChatBox'     : barejid + "__chatBox",
991                        'jidTo'                 : barejid,
992                                'path_jabberit' : path_jabberit
993        };
994
995        titleWindow = barejid.toLowerCase();
996                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
997
998        if( TrophyIM.rosterObj.roster[barejid] )
999        {
1000            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
1001            {
1002                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
1003            }
1004        }
1005
1006        // Position Top
1007        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
1008        if( TrophyIM.posWindow.top > 200 )
1009                TrophyIM.posWindow.top  = 100;
1010       
1011        // Position Left
1012        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
1013        if( TrophyIM.posWindow.left > 455 )
1014                TrophyIM.posWindow.left = 400;
1015       
1016        var _content = document.createElement( 'div' );
1017        _content.innerHTML = loadscript.parse( "chat_box", "chatBox.xsl", paramsChatBox);
1018        _content = _content.firstChild;
1019       
1020        var _messages           = _content.firstChild.firstChild;
1021        var _textarea           = _content.getElementsByTagName( 'textarea' ).item( 0 );
1022        var _send                       = _content.getElementsByTagName( 'input' ).item( 0 );
1023                var _chatStateOnOff     = _content.getElementsByTagName( 'input' ).item( 1 );
1024
1025        var _send_message = function( )
1026        {
1027                if ( ! TrophyIM.sendMessage( barejid, _textarea.value ) )
1028                        return false;
1029
1030                // Add Message in chatBox;
1031                TrophyIM.addMessage( _messages, barejid, {
1032                        contact : "<font style='font-weight:bold; color:red;'>" + i18n.ME + "</font>",
1033                        msg : "<br/>" + _textarea.value
1034                } );
1035
1036                _textarea.value = '';
1037                _textarea.focus( );
1038        };
1039               
1040                var composingTimer_ = 0;
1041                var isComposing_ = 0;
1042                var timeCounter;
1043
1044                var setComposing = function( )
1045                {
1046                        var checkComposing = function()
1047                        {
1048                if (!isComposing_) {
1049                        // User stopped composing
1050                        composingTimer_ = 0;
1051                        clearInterval(timeCounter);
1052                        TrophyIM.sendContentMessage(barejid, 'paused');
1053                } else {
1054                        TrophyIM.sendContentMessage(barejid, 'composing');
1055                }
1056                isComposing_ = 0; // Reset composing
1057                }
1058
1059                if (!composingTimer_) {
1060                /* User (re)starts composing */
1061                composingTimer_ = 1;
1062                timeCounter = setInterval(checkComposing,4000);
1063                }
1064                isComposing_ = 1;
1065        };
1066
1067        loadscript.configEvents( _send, 'onclick', _send_message );
1068                loadscript.configEvents( _textarea, 'onkeyup', function( e )
1069                {
1070                        if ( e.keyCode == 13 ){
1071                                _send_message( );
1072                                // User stopped composing
1073                composingTimer_ = 0;
1074                clearInterval(timeCounter);
1075                        }else{
1076                                if (_chatStateOnOff.value == 'on')
1077                                        setComposing();
1078                        }
1079                } );       
1080
1081        var winChatBox =
1082        {
1083                         id_window              : "window_chat_area_" + barejid,
1084                         barejid                : barejid,
1085                         width                  : 387,
1086                         height                 : 375,
1087                         top                    : TrophyIM.posWindow.top,
1088                         left                   : TrophyIM.posWindow.left,
1089                         draggable              : true,
1090                         visible                : "display",
1091                         resizable              : true,
1092                         zindex                 : loadscript.getZIndex(),
1093                         title                  : titleWindow,
1094                         closeAction    : "hidden",
1095                         content                : _content     
1096        }
1097       
1098                _win = _winBuild(winChatBox);
1099
1100        // Notification New Message
1101        loadscript.notification(barejid);
1102       
1103        // Photo User;
1104                loadscript.getPhotoUser(barejid);
1105               
1106                _textarea.focus( );
1107               
1108                return ( _messages = _win.content( ).firstChild );
1109    },
1110
1111        /** Function: makeChatRoom
1112    *
1113    *
1114    *
1115    */
1116   
1117    makeChatRoom : function()
1118    {
1119        var jidChatRoom = arguments[0];
1120        var titleWindow = "ChatRoom - " + arguments[1];
1121       
1122        var paramsChatRoom =
1123        {
1124                        'idChatRoom'    : jidChatRoom + "__roomChat",
1125                        'jidTo'                 : jidChatRoom,
1126                        'lang_Send'             : i18n.SEND,
1127                        'lang_Leave_ChatRoom' : i18n.LEAVE_CHATROOM,
1128                                'path_jabberit' : path_jabberit
1129        };
1130
1131        // Position Top
1132        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
1133        if( TrophyIM.posWindow.top > 200 )
1134                TrophyIM.posWindow.top  = 100;
1135       
1136        // Position Left
1137        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
1138        if( TrophyIM.posWindow.left > 455 )
1139                TrophyIM.posWindow.left = 400;
1140
1141        var _content = document.createElement( 'div' );
1142        _content.innerHTML = loadscript.parse( "chat_room", "chatRoom.xsl", paramsChatRoom );
1143        _content = _content.firstChild;
1144       
1145        var _messages           = _content.firstChild.firstChild;
1146        var _textarea           = _content.getElementsByTagName( 'textarea' ).item( 0 );
1147        var _send                       = _content.getElementsByTagName( 'input' ).item( 0 );
1148        var _leaveChatRoom      = _content.getElementsByTagName( 'input' ).item( 1 );
1149       
1150        var _send_message = function( )
1151        {
1152                if ( ! TrophyIM.sendMessageChatRoom( jidChatRoom, _textarea.value ) )
1153                        return false;
1154               
1155                _textarea.value = '';
1156               
1157                _textarea.focus( );
1158        };
1159       
1160        loadscript.configEvents( _send, 'onclick', _send_message );
1161        loadscript.configEvents( _leaveChatRoom, 'onclick', function( )
1162        {
1163                TrophyIM.leaveChatRoom( jidChatRoom );
1164
1165                setTimeout( function()
1166                {
1167                        _winBuild('window_chat_room_' + jidChatRoom, 'remove');
1168                       
1169                }, 500 );
1170               
1171        });
1172       
1173                loadscript.configEvents( _textarea, 'onkeyup', function( e )
1174                {
1175                        if ( e.keyCode == 13 )
1176                        {
1177                                _send_message( );
1178                        }
1179                });       
1180       
1181        var winChatRoom =
1182        {
1183                         id_window              : "window_chat_room_" + arguments[0],
1184                         barejid                : jidChatRoom,
1185                         width                  : 500,
1186                         height                 : 450,
1187                         top                    : TrophyIM.posWindow.top,
1188                         left                   : TrophyIM.posWindow.left,
1189                         draggable              : true,
1190                         visible                : "display",
1191                         resizable              : true,
1192                         zindex                 : loadscript.getZIndex(),
1193                         title                  : titleWindow,
1194                         closeAction    : "hidden",
1195                         content                : _content     
1196        }
1197       
1198        _win = _winBuild(winChatRoom);
1199       
1200        return ( _messages = _win.content( ).firstChild );
1201       
1202    },
1203   
1204        /** Function addContacts
1205         *
1206         *  Parameters:
1207         *              (string) jidFrom         
1208         *      (string) jidTo
1209         *              (string) name
1210         *              (string) group   
1211         */
1212       
1213        addContact : function( jidTo, name, group )
1214        {
1215                // Add Contact
1216        var _id = TrophyIM.connection.getUniqueId('add');
1217                var newContact = $iq({type: 'set', id: _id });
1218                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1219                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
1220                        newContact = newContact.c('group').t(group).tree();
1221
1222                TrophyIM.connection.send(newContact);
1223        },
1224
1225    /** Function: add
1226     *
1227     *  Parameters:
1228     *    (string) msg - the message to add
1229     *    (string) jid - the jid of chat box to add the message to.
1230     */
1231       
1232    addMessage : function( chatBox, jid, msg )
1233    {
1234        // Get Smiles
1235        msg.msg = loadscript.getSmiles( msg.msg );
1236 
1237        var messageDiv  = document.createElement("div");
1238                messageDiv.style.margin = "3px 0px 1em 3px";
1239        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
1240               
1241        chatBox.appendChild(messageDiv);
1242        chatBox.scrollTop = chatBox.scrollHeight;
1243    },
1244       
1245    /** Function : renameContact
1246     *
1247     *
1248     */
1249   
1250    renameContact : function( jid )
1251    {
1252        // Name
1253        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
1254
1255                if(( name = prompt(i18n.ASK_NEW_NAME_QUESTION + name + "!", name )))
1256                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1257                                name = "";
1258
1259                if( name == null || name == "")
1260                        name = "";
1261               
1262        var jidTo = jid
1263        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
1264        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1265       
1266        TrophyIM.addContact( jidTo, name, group );
1267       
1268        document.getElementById('itenContact_' + jid ).innerHTML = name;
1269    },
1270   
1271    /** Function : renameGroup
1272     *
1273     *
1274     */
1275
1276    renameGroup : function( jid )
1277    {
1278        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1279        var presence    = TrophyIM.rosterObj.roster[jid].presence;
1280       
1281                // Group
1282                if(( group = prompt( i18n.ASK_NEW_GROUP_QUESTION, group )))
1283                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1284                                group = "";
1285
1286                if( group == null || group == "")
1287                        group = "";
1288
1289        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
1290        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
1291                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
1292
1293                TrophyIM.rosterObj.removeContact( jid );
1294               
1295                TrophyIM.addContact( jidTo, name, group );
1296       
1297                document.getElementById("JabberIMRoster").innerHTML = "";
1298               
1299        TrophyIM.renderRoster();
1300       
1301        setTimeout(function()
1302        {
1303                for( var i in presence )
1304                {
1305                        if ( presence[ i ].constructor == Function )
1306                                continue;
1307                               
1308                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
1309                }
1310        },500);
1311    },
1312
1313    /** Function createChatRooms
1314     *
1315     *
1316     */
1317   
1318    createChatRooms : function()
1319    {
1320        var nickName     = document.getElementById('nickName_chatRoom_jabberit').value;
1321        var nameChatRoom = document.getElementById('name_ChatRoom_jabberit').value;
1322       
1323        var _from               = Base64.decode( loadscript.getUserCurrent().jid ) + TROPHYIM_RESOURCE;
1324                var _to                 = escape( nameChatRoom ) + "@" + TROPHYIM_CHATROOM + "/" + nickName ;
1325                var new_room    = $pres( {from: _from, to: _to } ).c( "x", { xmlns: Strophe.NS.MUC } );
1326
1327                TrophyIM.connection.send( new_room.tree() );
1328    },
1329   
1330    /** Function : joinRoom
1331     *
1332     *
1333     */
1334   
1335    joinChatRoom : function( roomName )
1336    {
1337        var presence = $pres( {from: TrophyIM.connection.jid, to: roomName} ).c("x",{xmlns: Strophe.NS.MUC});
1338       
1339                TrophyIM.connection.send( presence );
1340    },
1341   
1342    /** Function : Leave Chat Room
1343     *
1344     *
1345     */
1346   
1347    leaveChatRoom : function( roomName )
1348    {
1349        var room_nick   = roomName;
1350       
1351        var presenceid  = TrophyIM.connection.getUniqueId();
1352       
1353        var presence    = $pres( {type: "unavailable", id: presenceid, from: TrophyIM.connection.jid, to: room_nick} ).c("x",{xmlns: Strophe.NS.MUC});
1354       
1355        TrophyIM.connection.send( presence );       
1356    },
1357   
1358    /** Function : getlistRooms
1359     *
1360     *
1361     */
1362   
1363    getListRooms : function()
1364    {
1365        var _error_return = function(element)
1366        {
1367                alert( " ERROR : " + element );
1368        };
1369       
1370                var iq = $iq({to: "conference.im.pr.gov.br", type: "get"}).c("query",{xmlns: Strophe.NS.DISCO_ITEMS});                 
1371               
1372        TrophyIM.connection.sendIQ( iq, loadscript.listRooms, _error_return, 500 );             
1373    },
1374   
1375    /** Function: removeContact
1376     *
1377     *  Parameters:
1378     *          (string) jidTo
1379     */
1380   
1381    removeContact : function( jidTo )
1382    {
1383        var divItenContact       = null;
1384
1385        if( ( divItenContact = document.getElementById('itenContact_' + jidTo )))
1386        {       
1387                // Remove Contact
1388                var _id = TrophyIM.connection.getUniqueId();   
1389                var delContact  = $iq({type: 'set', id: _id})
1390                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1391                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
1392
1393                TrophyIM.connection.send( delContact );
1394               
1395                        loadscript.removeElement( document.getElementById('itenContactNotification_' + jidTo ) );
1396               
1397                var spanShow = document.getElementById('span_show_itenContact_' + jidTo )
1398                        spanShow.parentNode.removeChild(spanShow);
1399               
1400                loadscript.removeGroup( divItenContact.parentNode );
1401               
1402                divItenContact.parentNode.removeChild(divItenContact);
1403        }
1404    },
1405   
1406    /** Function: renderRoster
1407     *
1408     *  Renders roster, looking only for jids flagged by setPresence as having
1409     *  changed.
1410     */
1411   
1412        renderRoster : function()
1413        {
1414                var roster_div = document.getElementById('JabberIMRoster');
1415               
1416                if( roster_div )
1417                {
1418                        var users = new Array();
1419                       
1420                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1421                       
1422                        if( loading_gif.style.display == "block" )
1423                                loading_gif.style.display = "none";
1424                               
1425                        for( var user in TrophyIM.rosterObj.roster )
1426                        {
1427                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
1428                                        continue;
1429
1430                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
1431                        }
1432
1433                        users.sort();
1434                       
1435                        var groups              = new Array();
1436                        var flagGeral   = false;
1437                       
1438                        for (var group in TrophyIM.rosterObj.groups)
1439                        {
1440                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
1441                                        continue;
1442                               
1443                                if( group )
1444                                        groups[groups.length] = group;
1445                               
1446                                if( group == "Geral" )
1447                                        flagGeral = true;
1448            }
1449           
1450                        if( !flagGeral && users.length > 0 )
1451                                groups[groups.length] = "Geral";
1452                               
1453                        groups.sort();
1454                       
1455                        for ( var i = 0; i < groups.length; i++ )
1456                        {
1457                                TrophyIM.renderGroups( groups[i] , roster_div );       
1458                        }
1459                       
1460                        TrophyIM.renderItensGroup( users, roster_div );
1461                }
1462                       
1463                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
1464        },
1465       
1466    /** Function: renderGroups
1467     *
1468     *
1469     */
1470       
1471        renderGroups: function( nameGroup, element )
1472        {
1473                var _addGroup = function()
1474                {
1475                        var _nameGroup  = nameGroup;
1476                        var _element    = element;
1477
1478                        var paramsGroup =
1479                        {
1480                                'nameGroup'     : _nameGroup,
1481                                'path_jabberit' : path_jabberit
1482                        }
1483                       
1484                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
1485                }
1486
1487                if( !element.hasChildNodes() )
1488                {
1489                        _addGroup();
1490                }
1491                else
1492                {
1493                        var _NodeChild  = element.firstChild;
1494                        var flagAdd             = false;
1495                       
1496                        while( _NodeChild )
1497                        {
1498                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1499                                {
1500                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
1501                                        {
1502                                                flagAdd = true;
1503                                        }
1504                                }
1505                               
1506                                _NodeChild = _NodeChild.nextSibling;
1507                        }
1508
1509                        if( !flagAdd )
1510                        {
1511                                _addGroup();
1512                        }
1513                }
1514        },
1515
1516    /** Function: renderItensGroup
1517     *
1518     *
1519     */
1520
1521        renderItensGroup : function( users, element )
1522        {
1523                var addItem = function()
1524                {
1525                        if( arguments.length > 0 )
1526                        {
1527                                // Get Arguments
1528                                var objContact  = arguments[0];
1529                                var group               = arguments[1];
1530                                var element             = arguments[2];
1531                                var showOffline = loadscript.getShowContactsOffline();
1532                               
1533                                // Presence e Status
1534                                var presence            = "unavailable";
1535                                var status                      = "";
1536                                var statusColor         = "black";
1537                                var statusDisplay       = "none";
1538                               
1539                                var _resource   = "";
1540                               
1541                                // Set Presence
1542                                var _presence = function(objContact)
1543                                {
1544                                        if (objContact.presence)
1545                                        {
1546                                                for (var resource in objContact.presence)
1547                                                {
1548                                                        if ( objContact.presence[resource].constructor == Function )
1549                                                                continue;
1550
1551                                                        if( objContact.presence[resource].show != 'invisible' )
1552                                                                presence = objContact.presence[resource].show;
1553
1554                                                        if( objContact.contact.subscription != "both")
1555                                                                presence = 'subscription';
1556                                                       
1557                                                        if( objContact.presence[resource].status )
1558                                                        {
1559                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1560                                                                statusDisplay   = "block";
1561                                                        }
1562                                                }
1563                                        }
1564                                };
1565                               
1566                                // Set Subscription
1567                                var _subscription = function( objContact )
1568                                {
1569                                        if( objContact.contact.subscription != "both" )
1570                                        {
1571                                                switch( objContact.contact.subscription )
1572                                                {
1573                                                        case "none" :
1574                                                               
1575                                                                status          = " (( " + i18n.ASK_FOR_AUTH  + " )) ";
1576                                                                statusColor     = "red";
1577                                                                break;
1578       
1579                                                        case "to" :
1580                                                               
1581                                                                status          = " (( " + i18n.CONTACT_ASK_FOR_AUTH  + " )) ";
1582                                                                statusColor     = "orange";
1583                                                                break;
1584       
1585                                                        case "from" :
1586                                                               
1587                                                                status          = " (( " + i18n.AUTHORIZED + " )) ";
1588                                                                statusColor = "green";
1589                                                                break;
1590                                                               
1591                                                        case "subscribe" :
1592                                                               
1593                                                                status          = " (( " + i18n.AUTH_SENT  + " )) ";
1594                                                                statusColor     = "red";       
1595                                                                break;
1596
1597                                                        case "not-in-roster" :
1598                                                               
1599                                                                status          = " (( " + i18n.ASK_FOR_AUTH_QUESTION  + " )) ";
1600                                                                statusColor     = "orange";     
1601                                                                break;
1602                                                               
1603                                                        default :
1604                                                               
1605                                                                break;
1606                                                }
1607
1608                                                statusDisplay = "block";
1609                                        }
1610                                };
1611
1612                                if( objContact.contact.subscription != "remove")
1613                                {
1614                                        var itensJid    = document.getElementById( "itenContact_" + objContact.contact.jid );
1615                                       
1616                                        if( itensJid == null )
1617                                        {
1618                                                // Name
1619                                                var nameContact = "";                                   
1620                                               
1621                                                if ( objContact.contact.name )
1622                                                        nameContact = objContact.contact.name;
1623                                                else
1624                                                {
1625                                                        nameContact = objContact.contact.jid;
1626                                                        nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1627                                                }
1628                                               
1629                                                // Get Presence
1630                                                _presence(objContact);
1631                                               
1632                                                var paramsContact =
1633                                                {
1634                                                        divDisplay              : "block",
1635                                                        id                              : 'itenContact_' + objContact.contact.jid ,
1636                                                        jid                             : objContact.contact.jid,
1637                                                        nameContact     : nameContact,
1638                                                        path_jabberit   : path_jabberit,
1639                                                        presence                : presence,
1640                                                        spanDisplay             : statusDisplay,
1641                                                        status                  : status,
1642                                                        statusColor             : "black",
1643                                                        subscription    : objContact.contact.subscription,
1644                                                        resource                : _resource
1645                                                }
1646                                               
1647                                                // Get Authorization
1648                                                _subscription( objContact );
1649                                               
1650                                                if( group != "")
1651                                                {
1652                                                        var _NodeChild          = element.firstChild;
1653                                                       
1654                                                        while( _NodeChild )
1655                                                        {
1656                                                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1657                                                                {
1658                                                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1659                                                                        {
1660                                                                                _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1661                                                                        }
1662                                                                }
1663       
1664                                                                _NodeChild = _NodeChild.nextSibling;
1665                                                        }
1666                                                }       
1667                                        }
1668                                        else
1669                                        {
1670                                                // Get Presence
1671                                                _presence(objContact);
1672       
1673                                                var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1674                                                        is_open = is_open.indexOf("arrow_down.gif");
1675       
1676                                                // Get Authorization
1677                                                _subscription( objContact );
1678                                               
1679                                                // Set subscription
1680                                                itensJid.setAttribute('subscription', objContact.contact.subscription );
1681                                               
1682                                                with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ) )
1683                                                {
1684                                                        if( presence == "unavailable" && !showOffline )
1685                                                        {
1686                                                                style.display = "none";
1687                                                        }
1688                                                        else
1689                                                        {
1690                                                                if( is_open > 0 )
1691                                                                {
1692                                                                        style.display   = statusDisplay;
1693                                                                        style.color             = statusColor;
1694                                                                        innerHTML               = status;
1695                                                                }
1696                                                        }
1697                                                }
1698                                               
1699                                                if( presence == "unavailable" && !showOffline )
1700                                                {
1701                                                        itensJid.style.display = "none";
1702                                                }
1703                                                else
1704                                                {
1705                                                        if( is_open > 0 )
1706                                                        {
1707                                                                itensJid.style.display = "block";
1708                                                        }
1709                                                }
1710                                               
1711                                                itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1712                                        }
1713       
1714                                        // Contact OffLine
1715                                        if( !objContact.presence && !showOffline )
1716                                        {
1717                                                if( objContact.contact.subscription != "remove" )
1718                                                {
1719                                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ))
1720                                                        {
1721                                                                style.display   = "none";
1722                                                        }
1723               
1724                                                        with ( document.getElementById('itenContact_' + objContact.contact.jid ) )
1725                                                        {
1726                                                                style.display   = "none";
1727                                                        }
1728                                                }
1729                                        }
1730                                }
1731                        }
1732                };
1733               
1734                var flag = false;
1735               
1736                for( var i = 0 ; i < users.length; i++ )
1737                {
1738                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode( loadscript.getUserCurrent().jid) )
1739                        {
1740                                var _subscription = TrophyIM.rosterObj.roster[users[i]].contact.subscription;
1741                               
1742                                if( _subscription === "to" )
1743                                {
1744                                        flag = true;
1745                                }
1746                               
1747                                if(  _subscription === "not-in-roster")
1748                                {
1749                                        flag = true;
1750                                }
1751                               
1752                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1753                                {
1754                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1755                                       
1756                                        if( groups.length > 0 )
1757                                        {
1758                                                for( var j = 0; j < groups.length; j++ )
1759                                                {
1760                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element );
1761                                                }
1762                                        }
1763                                        else
1764                                        {
1765                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1766                                        }
1767                                }
1768                                else
1769                                {
1770                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1771                                }
1772                        }
1773                }
1774               
1775                if( flag )
1776                {
1777                        if ( TrophyIM.controll.notificationNewUsers == 0 )
1778                        {
1779                                loadscript.enabledNotificationNewUsers();
1780                                TrophyIM.controll.notificationNewUsers++;
1781                        }
1782                }
1783                else
1784                {
1785                        loadscript.disabledNotificationNewUsers();
1786                        TrophyIM.controll.notificationNewUsers = 0;
1787                }
1788        },
1789
1790    /** Function: rosterClick
1791     *
1792     *  Handles actions when a roster item is clicked
1793     */
1794   
1795        rosterClick : function(fulljid)
1796        {
1797        TrophyIM.makeChat(fulljid);
1798    },
1799
1800        /** Function SetAutorization
1801         *
1802         */
1803
1804        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1805        {
1806        var _id = TrophyIM.connection.getUniqueId();
1807       
1808        TrophyIM.connection.send($pres( ).attrs({ from: jidFrom, to: jidTo, type: _typeSubscription, id: _id }).tree());
1809        },
1810
1811        /** Function: setPresence
1812     *
1813     */
1814
1815        setPresence : function( _type )
1816        {
1817                if( _type != 'status')
1818                {
1819                        if( _type == "unavailable" &&  TrophyIM.statusConn.connected )
1820                        {
1821                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1822                               
1823                                if( TrophyIM._timeOut.renderRoster != null )
1824                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1825                               
1826                                if( TrophyIM.statusConn.connected )
1827                                        TrophyIM.connection.send($pres({type : _type}).tree());
1828                               
1829                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1830                        {
1831                                if( TrophyIM.connection._requests[i] )
1832                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1833                        }
1834                               
1835                                TrophyIM.logout();
1836                               
1837                        loadscript.clrAllContacts();
1838                       
1839                        delete TrophyIM.rosterObj.roster;
1840                        delete TrophyIM.rosterObj.groups;
1841                       
1842                        setTimeout(function()
1843                        {
1844                                        if( loading_gif.style.display == "block" )
1845                                                loading_gif.style.display = "none";
1846                        }, 1000);
1847                        }
1848                        else
1849                        {
1850                                if( !TrophyIM.autoConnection.connect )
1851                                {
1852                                        TrophyIM.autoConnection.connect = true;
1853                                        TrophyIM.load();
1854                                }
1855                                else
1856                                {
1857                                        if( TrophyIM.statusConn.connected )
1858                                        {
1859                                                if( loadscript.getStatusMessage() != "" )
1860                                                {
1861                                                        var _presence = $pres( );
1862                                                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1863                                                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1864                                                       
1865                                                        TrophyIM.connection.send( _presence.tree() );
1866                                                }
1867                                                else
1868                                                {
1869                                                        TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1870                                                }
1871                                        }
1872                                }
1873                        }
1874                }
1875                else
1876                {
1877                        var _show       = "available";
1878                        var _status     = "";
1879                       
1880                        if( arguments.length < 2 )
1881                        {
1882                                if( loadscript.getStatusMessage() != "" )
1883                                        _status = prompt(i18n.TYPE_YOUR_MSG, loadscript.getStatusMessage());
1884                                else
1885                                        _status = prompt(i18n.TYPE_YOUR_MSG);
1886                               
1887                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1888                               
1889                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1890                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1891                        }
1892                        else
1893                        {
1894                                _status = arguments[1];
1895                        }
1896
1897                        for( var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1898                        {
1899                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1900                                continue;
1901                       
1902                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1903                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1904                        }
1905
1906                        if ( TrophyIM.statusConn.connected )
1907                        {
1908                                var _presence = $pres( );
1909                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1910                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1911                               
1912                                TrophyIM.connection.send( _presence.tree() );
1913                        }
1914                }
1915        },
1916       
1917        /** Function: sendMessage
1918     *
1919     *  Send message from chat input to user
1920     */
1921     
1922    sendMessage : function()
1923    {
1924                if (arguments.length > 0)
1925                {
1926                        var jidTo = arguments[0];
1927                        var message_input = arguments[1];
1928                       
1929                       
1930                        message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g, "");
1931                       
1932                        if (message_input != "") {
1933                       
1934                                // Send Message
1935                                var newMessage = $msg({
1936                                        to: jidTo,
1937                                        from: TrophyIM.connection.jid,
1938                                        type: 'chat'
1939                                });
1940                                newMessage = newMessage.c('body').t(message_input);
1941                                newMessage.up();
1942                                newMessage = newMessage.c('active').attrs({
1943                                        xmlns: 'http://jabber.org/protocol/chatstates'
1944                                });
1945                                // Send Message
1946                                TrophyIM.connection.send(newMessage.tree());
1947                               
1948                                return true;
1949                        }
1950                }
1951               
1952                return false;
1953    },
1954
1955        /** Function: sendMessage
1956    *
1957    *  Send message to ChatRoom
1958    */
1959   
1960    sendMessageChatRoom : function( room )
1961    {
1962        if( arguments.length > 0 )
1963        {
1964                var room_nick   = arguments[0];
1965                var message             = arguments[1];
1966                var msgid               = TrophyIM.connection.getUniqueId();
1967                var msg                 = $msg({to: room_nick, type: "groupchat", id: msgid}).c("body",{xmlns: Strophe.NS.CLIENT}).t(message);
1968               
1969                msg.up();//.c("x", {xmlns: "jabber:x:event"}).c("composing");
1970               
1971                TrophyIM.connection.send(msg);
1972               
1973                return true;
1974        }
1975    },
1976   
1977        /** Function: sendContentMessage
1978     *
1979     *  Send a content message from chat input to user
1980     */
1981        sendContentMessage : function()
1982    {
1983      if( arguments.length > 0 )
1984      {
1985         var jidTo = arguments[0];
1986         var state = arguments[1];
1987
1988         var newMessage = $msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'});
1989         newMessage = newMessage.c(state).attrs({xmlns : 'http://jabber.org/protocol/chatstates'});
1990         // Send content message
1991         TrophyIM.connection.send(newMessage.tree());
1992      }
1993    }
1994};
1995
1996/** Class: TrophyIMRoster
1997 *
1998 *
1999 *  This object stores the roster and presence info for the TrophyIMClient
2000 *
2001 *  roster[jid_lower]['contact']
2002 *  roster[jid_lower]['presence'][resource]
2003 */
2004function TrophyIMRoster()
2005{
2006    /** Constants: internal arrays
2007     *    (Object) roster - the actual roster/presence information
2008     *    (Object) groups - list of current groups in the roster
2009     *    (Array) changes - array of jids with presence changes
2010     */
2011    if (TrophyIM.JSONStore.store_working)
2012        {
2013        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
2014        this.roster = (data['roster'] != null) ? data['roster'] : {};
2015        this.groups = (data['groups'] != null) ? data['groups'] : {};
2016    }
2017        else
2018        {
2019        this.roster = {};
2020        this.groups = {};
2021    }
2022    this.changes = new Array();
2023   
2024        if (TrophyIM.constants.stale_roster)
2025        {
2026        for (var jid in this.roster)
2027                {
2028                        this.changes[this.changes.length] = jid;
2029        }
2030    }
2031
2032        /** Function: addChange
2033         *
2034         *  Adds given jid to this.changes, keeping this.changes sorted and
2035         *  preventing duplicates.
2036         *
2037         *  Parameters
2038         *    (String) jid : jid to add to this.changes
2039         */
2040         
2041        this.addChange = function(jid)
2042        {
2043                for (var c = 0; c < this.changes.length; c++)
2044                {
2045                        if (this.changes[c] == jid)
2046                        {
2047                                return;
2048                        }
2049                }
2050               
2051                this.changes[this.changes.length] = jid;
2052               
2053                this.changes.sort();
2054        }
2055       
2056    /** Function: addContact
2057     *
2058     *  Adds given contact to roster
2059     *
2060     *  Parameters:
2061     *    (String) jid - bare jid
2062     *    (String) subscription - subscription attribute for contact
2063     *    (String) name - name attribute for contact
2064     *    (Array)  groups - array of groups contact is member of
2065     */
2066   
2067        this.addContact = function(jid, subscription, name, groups )
2068        {
2069                if( subscription === "remove" )
2070        {
2071                        this.removeContact(jid);
2072        }
2073        else
2074        {
2075                        var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
2076                var jid_lower   = jid.toLowerCase();
2077       
2078                        if ( this.roster[jid_lower] )
2079                        {
2080                    this.roster[jid_lower]['contact'] = contact;
2081                }
2082                        else
2083                        {
2084                    this.roster[jid_lower] = {contact:contact};
2085                }
2086
2087                        groups = groups ? groups : [''];
2088               
2089                        for ( var g = 0; g < groups.length; g++ )
2090                        {
2091                                if ( !this.groups[groups[g]] )
2092                                {
2093                        this.groups[groups[g]] = {};
2094                    }
2095                   
2096                                this.groups[groups[g]][jid_lower] = jid_lower;
2097                }
2098        }
2099    }
2100   
2101    /** Function: getContact
2102     *
2103     *  Returns contact entry for given jid
2104     *
2105     *  Parameter: (String) jid - jid to return
2106     */
2107     
2108    this.getContact = function(jid)
2109        {
2110        if (this.roster[jid.toLowerCase()])
2111                {
2112            return this.roster[jid.toLowerCase()]['contact'];
2113        }
2114    }
2115
2116   /** Function: getPresence
2117        *
2118        *  Returns best presence for given jid as Array(resource, priority, show,
2119        *  status)
2120        *
2121        *  Parameter: (String) fulljid - jid to return best presence for
2122        */
2123         
2124        this.getPresence = function(fulljid)
2125        {
2126                var jid = Strophe.getBareJidFromJid(fulljid);
2127                var current = null;
2128                   
2129                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
2130                {
2131                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
2132                        {
2133                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
2134                                continue;
2135                       
2136                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
2137                                if (current == null)
2138                                {
2139                                        current = presence
2140                                }
2141                                else
2142                                {
2143                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
2144                                        || presence['show'] == "available") || (current['show'] != "chat" ||
2145                                        current['show'] != "available")))
2146                                        {
2147                                                current = presence
2148                                        }
2149                                }
2150                        }
2151                }
2152                return current;
2153        }
2154
2155        /** Function: groupHasChanges
2156         *
2157         *  Returns true if current group has members in this.changes
2158         *
2159         *  Parameters:
2160         *    (String) group - name of group to check
2161         */
2162         
2163        this.groupHasChanges = function(group)
2164        {
2165                for (var c = 0; c < this.changes.length; c++)
2166                {
2167                        if (this.groups[group][this.changes[c]])
2168                        {
2169                                return true;
2170                        }
2171                }
2172                return false;
2173        }
2174       
2175        /** Function removeContact
2176         *
2177         * Parameters
2178         *       (String) jid           
2179         */
2180         
2181         this.removeContact = function(jid)
2182         {
2183                if( this.roster[ jid ] )
2184                {
2185                        var groups = this.roster[ jid ].contact.groups;
2186                       
2187                        if( groups )
2188                        {
2189                                for ( var i = 0; i < groups.length; i++ )
2190                                {
2191                                        delete this.groups[ groups[ i ] ][ jid ];
2192                                }
2193       
2194                                for ( var i = 0; i < groups.length; i++ )
2195                                {
2196                                        var contacts = 0;
2197                                        for ( var contact in this.groups[ groups[ i ] ] )
2198                                        {
2199                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
2200                                                continue;
2201                                       
2202                                                contacts++;
2203                                        }
2204               
2205                                        if ( ! contacts )
2206                                                delete this.groups[ groups[ i ] ];
2207                                }
2208                        }
2209       
2210                        // Delete Object roster
2211                        if( this.roster[jid] )
2212                                delete this.roster[jid];
2213                }
2214         }
2215         
2216    /** Function: setPresence
2217     *
2218     *  Sets presence
2219     *
2220     *  Parameters:
2221     *    (String) fulljid: full jid with presence
2222     *    (Integer) priority: priority attribute from presence
2223     *    (String) show: show attribute from presence
2224     *    (String) status: status attribute from presence
2225     */
2226   
2227        this.setPresence = function(fulljid, priority, show, status)
2228        {
2229                var barejid             = Strophe.getBareJidFromJid(fulljid);
2230        var resource    = Strophe.getResourceFromJid(fulljid);
2231        var jid_lower   = barejid.toLowerCase();
2232       
2233        if( show != 'unavailable' || show != 'error' )
2234                {
2235            if (!this.roster[jid_lower])
2236                        {
2237                this.addContact( barejid, 'not-in-roster' );
2238            }
2239           
2240            var presence =
2241                        {
2242                resource        : resource,
2243                priority        : priority,
2244                show            : show,
2245                status          : status
2246            }
2247           
2248                        if (!this.roster[jid_lower]['presence'])
2249                        {
2250                this.roster[jid_lower]['presence'] = {};
2251            }
2252           
2253            this.roster[jid_lower]['presence'][resource] = presence;   
2254                }
2255    }
2256
2257        /** Fuction: save
2258         *
2259         *  Saves roster data to JSON store
2260         */
2261       
2262        this.save = function()
2263        {
2264                if (TrophyIM.JSONStore.store_working)
2265                {
2266                        TrophyIM.JSONStore.setData({roster:this.roster,
2267                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
2268                        chat_history:TrophyIM.chatHistory});
2269                }
2270        }
2271
2272}
2273/** Class: TrophyIMJSONStore
2274 *
2275 *
2276 *  This object is the mechanism by which TrophyIM stores and retrieves its
2277 *  variables from the url provided by TROPHYIM_JSON_STORE
2278 *
2279 */
2280function TrophyIMJSONStore() {
2281    this.store_working = false;
2282    /** Function _newXHR
2283     *
2284     *  Set up new cross-browser xmlhttprequest object
2285     *
2286     *  Parameters:
2287     *    (function) handler = what to set onreadystatechange to
2288     */
2289     this._newXHR = function (handler) {
2290        var xhr = null;
2291        if (window.XMLHttpRequest) {
2292            xhr = new XMLHttpRequest();
2293            if (xhr.overrideMimeType) {
2294            xhr.overrideMimeType("text/xml");
2295            }
2296        } else if (window.ActiveXObject) {
2297            xhr = new ActiveXObject("Microsoft.XMLHTTP");
2298        }
2299        return xhr;
2300    }
2301    /** Function getData
2302     *  Gets data from JSONStore
2303     *
2304     *  Parameters:
2305     *    (Array) vars = Variables to get from JSON store
2306     *
2307     *  Returns:
2308     *    Object with variables indexed by names given in parameter 'vars'
2309     */
2310    this.getData = function(vars) {
2311        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2312            Strophe.debug("Retrieving JSONStore data");
2313            var xhr = this._newXHR();
2314            var getdata = "get=" + vars.join(",");
2315            try {
2316                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2317            } catch (e) {
2318                Strophe.error("JSONStore open failed.");
2319                return false;
2320            }
2321            xhr.setRequestHeader('Content-type',
2322            'application/x-www-form-urlencoded');
2323            xhr.setRequestHeader('Content-length', getdata.length);
2324            xhr.send(getdata);
2325            if (xhr.readyState == 4 && xhr.status == 200) {
2326                try {
2327                    var dataObj = JSON.parse(xhr.responseText);
2328                    return this.emptyFix(dataObj);
2329                } catch(e) {
2330                    Strophe.error("Could not parse JSONStore response" +
2331                    xhr.responseText);
2332                    return false;
2333                }
2334            } else {
2335                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2336                return false;
2337            }
2338        }
2339    }
2340    /** Function emptyFix
2341     *    Fix for bugs in external JSON implementations such as
2342     *    http://bugs.php.net/bug.php?id=41504.
2343     *    A.K.A. Don't use PHP, people.
2344     */
2345    this.emptyFix = function(obj) {
2346        if (typeof(obj) == "object") {
2347            for (var i in obj) {
2348                        if ( obj[i].constructor == Function )
2349                                continue;
2350                       
2351                if (i == '_empty_') {
2352                    obj[""] = this.emptyFix(obj['_empty_']);
2353                    delete obj['_empty_'];
2354                } else {
2355                    obj[i] = this.emptyFix(obj[i]);
2356                }
2357            }
2358        }
2359        return obj
2360    }
2361    /** Function delData
2362     *    Deletes data from JSONStore
2363     *
2364     *  Parameters:
2365     *    (Array) vars  = Variables to delete from JSON store
2366     *
2367     *  Returns:
2368     *    Status of delete attempt.
2369     */
2370    this.delData = function(vars) {
2371        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2372            Strophe.debug("Retrieving JSONStore data");
2373            var xhr = this._newXHR();
2374            var deldata = "del=" + vars.join(",");
2375            try {
2376                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2377            } catch (e) {
2378                Strophe.error("JSONStore open failed.");
2379                return false;
2380            }
2381            xhr.setRequestHeader('Content-type',
2382            'application/x-www-form-urlencoded');
2383            xhr.setRequestHeader('Content-length', deldata.length);
2384            xhr.send(deldata);
2385            if (xhr.readyState == 4 && xhr.status == 200) {
2386                try {
2387                    var dataObj = JSON.parse(xhr.responseText);
2388                    return dataObj;
2389                } catch(e) {
2390                    Strophe.error("Could not parse JSONStore response");
2391                    return false;
2392                }
2393            } else {
2394                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2395                return false;
2396            }
2397        }
2398    }
2399    /** Function setData
2400     *    Stores data in JSONStore, overwriting values if they exist
2401     *
2402     *  Parameters:
2403     *    (Object) vars : Object containing named vars to store ({name: value,
2404     *    othername: othervalue})
2405     *
2406     *  Returns:
2407     *    Status of storage attempt
2408     */
2409    this.setData = function(vars)
2410    {
2411        if ( typeof(TROPHYIM_JSON_STORE) != undefined )
2412        {
2413            var senddata = "set=" + JSON.stringify(vars);
2414            var xhr = this._newXHR();
2415            try
2416            {
2417                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2418            }
2419            catch (e)
2420            {
2421                Strophe.error("JSONStore open failed.");
2422                return false;
2423            }
2424            xhr.setRequestHeader('Content-type',
2425            'application/x-www-form-urlencoded');
2426            xhr.setRequestHeader('Content-length', senddata.length);
2427            xhr.send(senddata);
2428            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
2429            "OK") {
2430                return true;
2431            } else {
2432                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2433                return false;
2434            }
2435        }
2436    }
2437   
2438    var testData = true;
2439   
2440    if (this.setData({testData:testData})) {
2441        var testResult = this.getData(['testData']);
2442        if (testResult && testResult['testData'] == true) {
2443            this.store_working = true;
2444        }
2445    }
2446}
2447/** Constants: Node types
2448 *
2449 * Implementations of constants that IE doesn't have, but we need.
2450 */
2451if (document.ELEMENT_NODE == null) {
2452    document.ELEMENT_NODE = 1;
2453    document.ATTRIBUTE_NODE = 2;
2454    document.TEXT_NODE = 3;
2455    document.CDATA_SECTION_NODE = 4;
2456    document.ENTITY_REFERENCE_NODE = 5;
2457    document.ENTITY_NODE = 6;
2458    document.PROCESSING_INSTRUCTION_NODE = 7;
2459    document.COMMENT_NODE = 8;
2460    document.DOCUMENT_NODE = 9;
2461    document.DOCUMENT_TYPE_NODE = 10;
2462    document.DOCUMENT_FRAGMENT_NODE = 11;
2463    document.NOTATION_NODE = 12;
2464}
2465
2466/** Function: importNode
2467 *
2468 *  document.importNode implementation for IE, which doesn't have importNode
2469 *
2470 *  Parameters:
2471 *    (Object) node - dom object
2472 *    (Boolean) allChildren - import node's children too
2473 */
2474if (!document.importNode) {
2475    document.importNode = function(node, allChildren) {
2476        switch (node.nodeType) {
2477            case document.ELEMENT_NODE:
2478                var newNode = document.createElement(node.nodeName);
2479                if (node.attributes && node.attributes.length > 0) {
2480                    for(var i = 0; i < node.attributes.length; i++) {
2481                        newNode.setAttribute(node.attributes[i].nodeName,
2482                        node.getAttribute(node.attributes[i].nodeName));
2483                    }
2484                }
2485                if (allChildren && node.childNodes &&
2486                node.childNodes.length > 0) {
2487                    for (var i = 0; i < node.childNodes.length; i++) {
2488                        newNode.appendChild(document.importNode(
2489                        node.childNodes[i], allChildren));
2490                    }
2491                }
2492                return newNode;
2493                break;
2494            case document.TEXT_NODE:
2495            case document.CDATA_SECTION_NODE:
2496            case document.COMMENT_NODE:
2497                return document.createTextNode(node.nodeValue);
2498                break;
2499        }
2500    };
2501}
2502
2503/**
2504 *
2505 * Bootstrap self into window.onload and window.onunload
2506 */
2507
2508var oldonunload = window.onunload;
2509
2510window.onunload = function()
2511{
2512        if( oldonunload )
2513        {
2514        oldonunload();
2515    }
2516       
2517        TrophyIM.setPresence('unavailable');
2518}
Note: See TracBrowser for help on using the repository browser.