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

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

Ticket #986 - Tratado as mensagens com tags em html para evitar ataques de XSS.

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