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

Revision 3320, 68.8 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Refeito metodo indexOf para nao conflitar com as chamadas dentro do Expresso.

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