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

Revision 3314, 68.6 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Na adicao de contatos ja esta sendo enviado o aceite do convite.

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