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

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