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

Revision 3118, 70.9 KB checked in by alexandrecorreia, 14 years ago (diff)

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

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