source: sandbox/jabberit_messenger/trophy_expresso/js/trophyim.js @ 2827

Revision 2827, 59.2 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Corrigido para nao deletar a conexao quando nao existe.

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