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

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