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

Revision 2799, 56.9 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Implementando recebimento/envio de mensagens para mostrar as imagens smiles.

  • 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     = null;
662               
663                if( document.getElementById(jid_lower + "__chatState") != null )
664                {
665                        chatBox = document.getElementById(jid_lower + "__chatState");
666                }
667                               
668                contact = barejid.toLowerCase();
669                contact = contact.substring(0, contact.indexOf('@'));
670           
671                if( TrophyIM.rosterObj.roster[barejid] )
672                {
673                        if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
674                        {
675                                contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
676                        }
677                }
678
679                // Message with body are "content message", this mean state active
680                if ( elems.length > 0 )
681                {
682                        state = "";
683
684                        if (type == 'chat' || type == 'normal')
685                        {
686                                var _message = document.createElement("div");
687                                _message.innerHTML = Strophe.getText(elems[0]);
688                               
689                                var scripts = _message.getElementsByTagName('script');
690                               
691                                for (var i = 0; i < scripts.length; i++)
692                                        _message.removeChild(scripts[i--]);
693                               
694                                _message.innerHTML = _message.innerHTML.replace(/^\s+|\s+$|^\n|\n$/g, "");
695                               
696                                // Get Smiles
697                                _message.innerHTML = loadscript.getSmiles( _message.innerHTML );
698                               
699                                if ( _message.hasChildNodes() )
700                                {
701                                        var message =
702                                        {
703                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + contact + "</font>",
704                                msg             : "</br>" + _message.innerHTML
705                        };
706                                       
707                                        TrophyIM.addMessage( TrophyIM.makeChat( from ), jid_lower, message );
708                                }
709                        }
710                }
711                // Message without body are "content message", this mean state is not active
712                else
713                {
714                        if( chatBox != null )
715                                state = TrophyIM.getChatState(msg);                     
716                }
717               
718                if( chatBox != null )
719                        chatBox.innerHTML = '<font style="font-weight:bold; color:grey; margin-left: 5px; float:right;">' + state + '</font>'; 
720               
721                return true;
722        },
723
724        /** Function: getChatState
725         *
726         *  Parameters:
727         *    (string) msg - the message to get chat state
728         *    (string) jid - the jid of chat box to update the chat state to.
729         */
730        getChatState : function(msg)
731        {
732                var     state =  msg.getElementsByTagName('inactive');
733               
734                if ( state.length > 0 )
735                {
736                return' está inativo...';
737                }
738                else
739                {
740                state = msg.getElementsByTagName('gone');
741            if ( state.length > 0 )
742            {
743                return ' saiu da conversa.';
744                        }
745            else
746            {
747                state = msg.getElementsByTagName('composing');
748                if ( state.length > 0 )
749                {
750                        return ' está digitando...';
751                                }
752                else
753                {
754                        state =  msg.getElementsByTagName('paused');
755                        if ( state.length > 0 )
756                        {
757                                return ' está parado...';
758                                        }
759                                }
760                        }
761                }
762               
763                return '';
764        },
765
766   
767    /** Function: makeChat
768     *
769     *  Make sure chat window to given fulljid exists, switching chat context to
770     *  given resource
771     */
772     
773    makeChat : function(fulljid)
774    {
775        var barejid             = Strophe.getBareJidFromJid(fulljid);
776        var titleWindow = "";
777
778        var paramsChatBox =
779        {
780                        'enabledPopUp'  : ( ( loadscript.getIsIE() ) ? "none" : "block" ),
781                        'idChatBox'     : barejid + "__chatBox",
782                        'jidTo'                 : barejid,
783                                'path_jabberit' : path_jabberit
784        };
785
786        titleWindow = barejid.toLowerCase();
787                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
788
789        if( TrophyIM.rosterObj.roster[barejid] )
790        {
791            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
792            {
793                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
794            }
795        }
796
797        // Position Top
798        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
799        if( TrophyIM.posWindow.top > 200 )
800                TrophyIM.posWindow.top  = 100;
801       
802        // Position Left
803        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
804        if( TrophyIM.posWindow.left > 455 )
805                TrophyIM.posWindow.left = 400;
806       
807        var _content = document.createElement( 'div' );
808        _content.innerHTML = loadscript.parse( "chat_box", "chatBox.xsl", paramsChatBox);
809        _content = _content.firstChild;
810       
811        var _messages = _content.firstChild.firstChild;
812        var _textarea = _content.getElementsByTagName( 'textarea' ).item( 0 );
813        var _send = _content.getElementsByTagName( 'input' ).item( 0 );
814
815        function _send_message( )
816        {
817                if ( ! TrophyIM.sendMessage( barejid, _textarea.value ) )
818                        return false;
819
820                // Add Message in chatBox;
821                TrophyIM.addMessage( _messages, barejid, {
822                        contact : "<font style='font-weight:bold; color:red;'>" + "Eu" + "</font>",
823                        msg : "<br/>" + _textarea.value
824                } );
825
826                _textarea.value = '';
827                _textarea.focus( );
828        }
829
830        loadscript.configEvents( _send, 'onclick', _send_message );
831                loadscript.configEvents( _textarea, 'onkeyup', function( e )
832                {
833                        if ( e.keyCode == 13 )
834                                _send_message( );
835                } );
836       
837        var winChatBox =
838        {
839                         id_window              : "window_chat_area_" + barejid,
840                         barejid                : barejid,
841                         width                  : 387,
842                         height                 : 375,
843                         top                    : TrophyIM.posWindow.top,
844                         left                   : TrophyIM.posWindow.left,
845                         draggable              : true,
846                         visible                : "display",
847                         resizable              : true,
848                         zindex                 : loadscript.getZIndex(),
849                         title                  : titleWindow,
850                         closeAction    : "hidden",
851                         content                : _content     
852        }
853       
854                _win = _winBuild(winChatBox);
855
856        // Notification New Message
857        loadscript.notification(barejid);
858       
859        // Photo User;
860                loadscript.getPhotoUser(barejid);
861               
862                _textarea.focus( );
863               
864                return ( _messages = _win.content( ).firstChild );
865    },
866
867        /** Function addContacts
868         *
869         *  Parameters:
870         *              (string) jidFrom         
871         *      (string) jidTo
872         *              (string) name
873         *              (string) group   
874         */
875       
876        addContact : function( jidTo, name, group )
877        {
878                // Add Contact
879        var _id = TrophyIM.connection.getUniqueId('add');
880                var newContact = $iq({type: 'set', id: _id });
881                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
882                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
883                        newContact = newContact.c('group').t(group).tree();
884
885                TrophyIM.connection.send(newContact);
886        },
887
888    /** Function: addMessage
889     *
890     *  Parameters:
891     *    (string) msg - the message to add
892     *    (string) jid - the jid of chat box to add the message to.
893     */
894       
895    addMessage : function(chatBox, jid, msg)
896    {
897        // Get Smiles
898        msg.msg = loadscript.getSmiles( msg.msg );
899 
900        var messageDiv  = document.createElement("div");
901                messageDiv.style.margin = "3px 0px 1em 3px";
902        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
903               
904        chatBox.appendChild(messageDiv);
905        chatBox.scrollTop = chatBox.scrollHeight;
906    },
907       
908    /** Function : renameContact
909     *
910     *
911     */
912   
913    renameContact : function( jid, index )
914    {
915        // Name
916        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
917
918                if(( name = prompt("Informe um novo nome para " + name + "!", name )))
919                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
920                                name = "";
921
922                if( name == null || name == "")
923                        name = "";
924               
925        var jidTo = jid
926        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
927        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
928       
929        TrophyIM.addContact( jidTo, name, group );
930       
931        document.getElementById('itenContact_' + jid + '_' + index).innerHTML = name;
932    },
933   
934    /** Function : renameGroup
935     *
936     *
937     */
938
939    renameGroup : function( jid, index)
940    {
941        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
942        var presence    = TrophyIM.rosterObj.roster[jid].presence;
943       
944                // Group
945                if(( group = prompt("Informe um novo grupo ou deixe em branco", group )))
946                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
947                                group = "";
948
949                if( group == null || group == "")
950                        group = "";
951
952        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
953        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
954                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
955
956                TrophyIM.rosterObj.removeContact( jid );
957               
958                TrophyIM.addContact( jidTo, name, group );
959       
960                document.getElementById("JabberIMRoster").innerHTML = "";
961               
962        TrophyIM.renderRoster();
963       
964        setTimeout(function()
965        {
966                for( var i in presence )
967                {
968                        if ( presence[ i ].constructor == Function )
969                                continue;
970                               
971                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
972                }
973        },500);
974    },
975   
976    /** Function: removeContact
977     *
978     *  Parameters:
979     *          (string) jidTo
980     */
981   
982    removeContact : function(jidTo, indexTo)
983    {
984        var divItenContact       = null;
985        var spanShow             = null;
986       
987        if( ( divItenContact = document.getElementById('itenContact_' + jidTo + '_' + indexTo )))
988        {       
989                spanShow = document.getElementById('span_show_itenContact_' + jidTo + '_' + indexTo )
990               
991                spanShow.parentNode.removeChild(spanShow);
992               
993                loadscript.removeGroup( divItenContact.parentNode );
994               
995                divItenContact.parentNode.removeChild(divItenContact);
996
997                // Remove Contact
998                        var _id = TrophyIM.connection.getUniqueId();   
999                var delContact  = $iq({type: 'set', id: _id})
1000                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1001                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
1002
1003                TrophyIM.connection.send( delContact );                 
1004                       
1005                // Remove Contact       
1006                var _id = TrophyIM.connection.getUniqueId();
1007                var _delContact_ = $iq({type: 'set', id: _id})
1008                        _delContact_ = _delContact_.c('query').attrs({xmlns : 'jabber:iq:private'});
1009                        _delContact_ = _delContact_.c('storage').attrs({xmlns : 'storage:metacontacts'}).tree();
1010
1011                TrophyIM.connection.send( _delContact_ );       
1012        }
1013    },
1014   
1015    /** Function: renderRoster
1016     *
1017     *  Renders roster, looking only for jids flagged by setPresence as having
1018     *  changed.
1019     */
1020   
1021        renderRoster : function()
1022        {
1023                var roster_div = document.getElementById('JabberIMRoster');
1024               
1025                if( roster_div )
1026                {
1027                        var users = new Array();
1028                       
1029                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1030                       
1031                        if( loading_gif.style.display == "block" )
1032                                loading_gif.style.display = "none";
1033                               
1034                        for( var user in TrophyIM.rosterObj.roster )
1035                        {
1036                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
1037                                        continue;
1038
1039                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
1040                        }
1041
1042                        users.sort();
1043                       
1044                        var groups              = new Array();
1045                        var flagGeral   = false;
1046                       
1047                        for (var group in TrophyIM.rosterObj.groups)
1048                        {
1049                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
1050                                        continue;
1051                               
1052                                if( group )
1053                                        groups[groups.length] = group;
1054                               
1055                                if( group == "Geral" )
1056                                        flagGeral = true;
1057            }
1058           
1059                        if( !flagGeral && users.length > 0 )
1060                                groups[groups.length] = "Geral";
1061                               
1062                        groups.sort();
1063                       
1064                        for ( var i = 0; i < groups.length; i++ )
1065                        {
1066                                TrophyIM.renderGroups( groups[i] , roster_div );       
1067                        }
1068                       
1069                        TrophyIM.renderItensGroup( users, roster_div );
1070                }
1071                       
1072                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
1073        },
1074       
1075    /** Function: renderGroups
1076     *
1077     *
1078     */
1079       
1080        renderGroups: function( nameGroup, element )
1081        {
1082                var _addGroup = function()
1083                {
1084                        var _nameGroup  = nameGroup;
1085                        var _element    = element;
1086
1087                        var paramsGroup =
1088                        {
1089                                'nameGroup'     : _nameGroup,
1090                                'path_jabberit' : path_jabberit
1091                        }
1092                       
1093                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
1094                }
1095
1096                if( !element.hasChildNodes() )
1097                {
1098                        _addGroup();
1099                }
1100                else
1101                {
1102                        var _NodeChild  = element.firstChild;
1103                        var flagAdd             = false;
1104                       
1105                        while( _NodeChild )
1106                        {
1107                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1108                                {
1109                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
1110                                        {
1111                                                flagAdd = true;
1112                                        }
1113                                }
1114                               
1115                                _NodeChild = _NodeChild.nextSibling;
1116                        }
1117
1118                        if( !flagAdd )
1119                        {
1120                                _addGroup();
1121                        }
1122                }
1123        },
1124
1125    /** Function: renderItensGroup
1126     *
1127     *
1128     */
1129
1130        renderItensGroup : function( users, element )
1131        {
1132                var addItem = function()
1133                {
1134                        if( arguments.length > 0 )
1135                        {
1136                                var objContact  = arguments[0];
1137                                var group               = arguments[1];
1138                                var element             = arguments[2];
1139                                var index               = arguments[3];
1140                                var showOffline = loadscript.getShowContactsOffline();
1141                               
1142                                var itensJid    = document.getElementById( 'itenContact_' + objContact.contact.jid + '_' + index );
1143
1144                                if( itensJid == null )
1145                                {
1146                                        // Name
1147                                        var nameContact = "";                                   
1148                                       
1149                                        if ( objContact.contact.name )
1150                                                nameContact = objContact.contact.name;
1151                                        else
1152                                        {
1153                                                nameContact = objContact.contact.jid;
1154                                                nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1155                                        }
1156                                       
1157                                        // Presence e Status
1158                                        var presence            = "unavailable";
1159                                        var status                      = "";
1160                                        var statusDisplay       = "none";
1161                                       
1162                                        if (objContact.presence)
1163                                        {
1164                                                for (var resource in objContact.presence)
1165                                                {
1166                                                        if ( objContact.presence[resource].constructor == Function )
1167                                                                continue;
1168
1169                                                        if( objContact.presence[resource].show != 'invisible' )
1170                                                                presence = objContact.presence[resource].show;
1171
1172                                                        if( objContact.contact.subscription != "both")
1173                                                                presence = 'subscription';
1174                                                       
1175                                                        if( objContact.presence[resource].status )
1176                                                        {
1177                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1178                                                                statusDisplay   = "block";
1179                                                        }
1180                                                }
1181                                        }
1182                                       
1183                                        var paramsContact =
1184                                        {
1185                                                divDisplay              : "block",
1186                                                id                              : 'itenContact_' + objContact.contact.jid + '_' + index ,
1187                                                index                   : ((index == 0 ) ? "0" : index),
1188                                                jid                             : objContact.contact.jid,
1189                                                nameContact     : nameContact,
1190                                                path_jabberit   : path_jabberit,
1191                                                presence                : presence,
1192                                                spanDisplay             : statusDisplay,
1193                                                status                  : status,
1194                                                statusColor             : "black",
1195                                                subscription    : objContact.contact.subscription
1196                                        }
1197                                       
1198                                        // Authorization       
1199                                        if( objContact.contact.subscription != "both" )
1200                                        {
1201                                               
1202                                                switch(objContact.contact.subscription)
1203                                                {
1204                                                        case "none" :
1205                                                               
1206                                                                paramsContact.status            = " (( PEDIR AUTORIZAÇAO ! )) ";
1207                                                                paramsContact.statusColor       = "red";
1208                                                                break;
1209       
1210                                                        case "to" :
1211                                                               
1212                                                                paramsContact.status            = " (( CONTATO PEDE AUTORIZAÇÃO ! )) ";
1213                                                                paramsContact.statusColor       = "orange";
1214                                                                break;
1215       
1216                                                        case "from" :
1217                                                               
1218                                                                paramsContact.status            = " (( AUTORIZAR ? )) ";
1219                                                                paramsContact.statusColor       = "green";
1220                                                                break;
1221                                                               
1222                                                        case "subscribe" :
1223                                                               
1224                                                                paramsContact.status            = " (( AUTORIZAÇÃO ENVIADA ! )) ";
1225                                                                paramsContact.statusColor       = "red";       
1226                                                                break;
1227
1228                                                        case "not-in-roster" :
1229                                                               
1230                                                                paramsContact.status            = " (( QUERO ADICIONÁ-LO(A) ! POSSO ? )) ";
1231                                                                paramsContact.statusColor       = "orange";     
1232                                                                break;
1233                                                               
1234                                                        default:
1235                                                                paramsContact.status = " ( " + objContact.contact.subscription + " ) ";
1236                                                }
1237                                        }
1238                                       
1239                                        if( group != "")
1240                                        {
1241                                                var _NodeChild          = element.firstChild;
1242                                               
1243                                                while( _NodeChild )
1244                                                {
1245                                                        if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1246                                                        {
1247                                                                if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1248                                                                {
1249                                                                        _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1250                                                                }
1251                                                        }
1252
1253                                                        _NodeChild = _NodeChild.nextSibling;
1254                                                }
1255                                        }       
1256                                }
1257                                else
1258                                {
1259
1260                                        // Presence e Status
1261                                        var presence            = "unavailable";
1262                                        var status                      = "";
1263                                        var statusColor         = "black";
1264                                        var statusDisplay       = "none";
1265                                       
1266                                        if ( objContact.presence )
1267                                        {
1268                                                for ( var resource in objContact.presence )
1269                                                {
1270                                                        if ( objContact.presence[resource].constructor == Function )
1271                                                                continue;
1272
1273                                                        if( objContact.presence[resource].show != 'invisible' )
1274                                                                presence = objContact.presence[resource].show;
1275
1276                                                        if( objContact.contact.subscription != "both")
1277                                                                presence = 'subscription';
1278                                                       
1279                                                        if( objContact.presence[resource].status )
1280                                                        {
1281                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1282                                                                statusDisplay   = "block";
1283                                                        }
1284                                                }       
1285                                        }
1286                                               
1287                                        var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1288                                                is_open = is_open.indexOf("arrow_down.gif");
1289                                       
1290                                        // Authorization       
1291                                        if( objContact.contact.subscription != "both" )
1292                                        {
1293                                                switch(objContact.contact.subscription)
1294                                                {
1295                                                        case "none" :
1296                                                               
1297                                                                status          = " (( PEDIR AUTORIZAÇAO ! )) ";
1298                                                                statusColor     = "red";
1299                                                                break;
1300       
1301                                                        case "to" :
1302                                                               
1303                                                                status          = " (( CONTATO PEDE AUTORIZAÇÃO ! )) ";
1304                                                                statusColor     = "orange";
1305                                                                break;
1306       
1307                                                        case "from" :
1308                                                               
1309                                                                status          = " (( AUTORIZAR ? )) ";
1310                                                                statusColor = "green";
1311                                                                break;
1312                                                               
1313                                                        case "subscribe" :
1314                                                               
1315                                                                status          = " (( AUTORIZAÇÃO ENVIADA ! )) ";
1316                                                                statusColor     = "red";       
1317                                                                break;
1318
1319                                                        case "not-in-roster" :
1320                                                               
1321                                                                status          = " (( QUERO ADICIONÁ-LO(A) ! POSSO ? )) ";
1322                                                                statusColor     = "orange";     
1323                                                                break;
1324                                                               
1325                                                        default:
1326                                                                status = " ( " + objContact.contact.subscription + " ) ";
1327                                                }
1328
1329                                                statusDisplay = "block";
1330                                        }
1331                                       
1332                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ) )
1333                                        {
1334                                                /*if( is_open > 0 )
1335                                                {
1336                                                        style.display   = statusDisplay;
1337                                                        style.color             = statusColor;
1338                                                        innerHTML               = status;
1339                                                }*/
1340
1341                                                if( presence == "unavailable" && !showOffline )
1342                                                {
1343                                                        style.display = "none";
1344                                                }
1345                                                else
1346                                                {
1347                                                        if( is_open > 0 )
1348                                                        {
1349                                                                style.display   = statusDisplay;
1350                                                                style.color             = statusColor;
1351                                                                innerHTML               = status;
1352                                                        }
1353                                                }
1354                                        }
1355                                       
1356                                        if( presence == "unavailable" && !showOffline )
1357                                                itensJid.style.display = "none";
1358                                        else
1359                                        {
1360                                                if( is_open > 0 )
1361                                                {
1362                                                        itensJid.style.display = "block";
1363                                                }
1364                                        }
1365                                       
1366                                        itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1367                                }
1368
1369                                // Contact OffLine
1370                                if( !objContact.presence && !showOffline )
1371                                {
1372                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ))
1373                                        {
1374                                                style.display   = "none";
1375                                        }
1376
1377                                        with ( document.getElementById('itenContact_' + objContact.contact.jid + '_' + index ) )
1378                                        {
1379                                                style.display   = "none";
1380                                        }
1381                                }
1382                        }
1383                }
1384               
1385                for( var i = 0 ; i < users.length; i++ )
1386                {
1387                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode(loadscript.getUserCurrent().jid) )
1388                        {
1389                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1390                                {
1391                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1392                                       
1393                                        if( groups.length > 0 )
1394                                        {
1395                                                for( var j = 0; j < groups.length; j++ )
1396                                                {
1397                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element, j );
1398                                                }
1399                                        }
1400                                        else
1401                                        {
1402                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1403                                        }
1404                                }
1405                                else
1406                                {
1407                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1408                                }
1409                        }
1410                }       
1411        },
1412
1413    /** Function: rosterClick
1414     *
1415     *  Handles actions when a roster item is clicked
1416     */
1417   
1418        rosterClick : function(fulljid)
1419        {
1420        TrophyIM.makeChat(fulljid);
1421    },
1422
1423        /** Function SetAutorization
1424         *
1425         */
1426
1427        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1428        {
1429        var _id = TrophyIM.connection.getUniqueId();
1430       
1431        TrophyIM.connection.send($pres( ).attrs( {to: jidTo, from: jidFrom, type: _typeSubscription, id: _id}).tree());
1432        },
1433   
1434        /** Function: setPresence
1435     *
1436     */
1437
1438        setPresence : function( _type )
1439        {
1440                if( _type != 'status')
1441                {
1442                        if( _type == "unavailable")
1443                        {
1444                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1445                               
1446                                if( TrophyIM._timeOut.renderRoster != null )
1447                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1448                               
1449                                if( TrophyIM.statusConn.connected )
1450                                        TrophyIM.connection.send($pres({type : _type}).tree());
1451                               
1452                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1453                        {
1454                                if( TrophyIM.connection._requests[i] )
1455                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1456                        }
1457                               
1458                                TrophyIM.logout();
1459                               
1460                        loadscript.clrAllContacts();
1461                       
1462                        delete TrophyIM.rosterObj.roster;
1463                        delete TrophyIM.rosterObj.groups;
1464                       
1465                        setTimeout(function()
1466                        {
1467                                        if( loading_gif.style.display == "block" )
1468                                                loading_gif.style.display = "none";
1469                        }, 1000);
1470                        }
1471                        else
1472                        {
1473                                if( !TrophyIM.autoConnection.connect )
1474                                {
1475                                        TrophyIM.autoConnection.connect = true;
1476                                        TrophyIM.load();
1477                                }
1478                                else
1479                                {
1480                                        if( TrophyIM.statusConn.connected )
1481                                        {
1482                                                if( loadscript.getStatusMessage() != "" )
1483                                                {
1484                                                        var _presence = $pres( );
1485                                                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1486                                                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1487                                                       
1488                                                        TrophyIM.connection.send( _presence.tree() );
1489                                                }
1490                                                else
1491                                                {
1492                                                        TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1493                                                }
1494                                        }
1495                                }
1496                        }
1497                }
1498                else
1499                {
1500                        var _show       = "available";
1501                        var _status     = "";
1502                       
1503                        if( arguments.length < 2 )
1504                        {
1505                                if( loadscript.getStatusMessage() != "" )
1506                                        _status = prompt("Digite sua mensagem !!!", loadscript.getStatusMessage());
1507                                else
1508                                        _status = prompt("Digite sua mensagem !!!");
1509                               
1510                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1511                               
1512                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1513                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1514                        }
1515                        else
1516                        {
1517                                _status = arguments[1];
1518                        }
1519
1520                        for(var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1521                        {
1522                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1523                                continue;
1524                       
1525                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1526                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1527                        }
1528
1529                        if ( TrophyIM.statusConn.connected )
1530                        {
1531                                var _presence = $pres( );
1532                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1533                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1534                               
1535                                TrophyIM.connection.send( _presence.tree() );
1536                        }
1537                }
1538        },
1539       
1540        /** Function: sendMessage
1541     *
1542     *  Send message from chat input to user
1543     */
1544     
1545    sendMessage : function( _jidTo, _message )
1546    {
1547                _message = _message.replace(/^\s+|\s+$|^\n|\n$/g,"");
1548       
1549                if( _message != "" )
1550                {
1551                // Send Message
1552                TrophyIM.connection.send(
1553                        $msg( {
1554                                to: _jidTo, from: TrophyIM.connection.jid,
1555                                type: 'chat'
1556                        } ).c('body').t( _message ).tree()
1557                );
1558                return true;
1559                }
1560               
1561                return false;
1562    }
1563};
1564
1565/** Class: TrophyIMRoster
1566 *
1567 *
1568 *  This object stores the roster and presence info for the TrophyIMClient
1569 *
1570 *  roster[jid_lower]['contact']
1571 *  roster[jid_lower]['presence'][resource]
1572 */
1573function TrophyIMRoster()
1574{
1575    /** Constants: internal arrays
1576     *    (Object) roster - the actual roster/presence information
1577     *    (Object) groups - list of current groups in the roster
1578     *    (Array) changes - array of jids with presence changes
1579     */
1580    if (TrophyIM.JSONStore.store_working)
1581        {
1582        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1583        this.roster = (data['roster'] != null) ? data['roster'] : {};
1584        this.groups = (data['groups'] != null) ? data['groups'] : {};
1585    }
1586        else
1587        {
1588        this.roster = {};
1589        this.groups = {};
1590    }
1591    this.changes = new Array();
1592   
1593        if (TrophyIM.constants.stale_roster)
1594        {
1595        for (var jid in this.roster)
1596                {
1597                        this.changes[this.changes.length] = jid;
1598        }
1599    }
1600
1601        /** Function: addChange
1602         *
1603         *  Adds given jid to this.changes, keeping this.changes sorted and
1604         *  preventing duplicates.
1605         *
1606         *  Parameters
1607         *    (String) jid : jid to add to this.changes
1608         */
1609         
1610        this.addChange = function(jid)
1611        {
1612                for (var c = 0; c < this.changes.length; c++)
1613                {
1614                        if (this.changes[c] == jid)
1615                        {
1616                                return;
1617                        }
1618                }
1619               
1620                this.changes[this.changes.length] = jid;
1621               
1622                this.changes.sort();
1623        }
1624       
1625    /** Function: addContact
1626     *
1627     *  Adds given contact to roster
1628     *
1629     *  Parameters:
1630     *    (String) jid - bare jid
1631     *    (String) subscription - subscription attribute for contact
1632     *    (String) name - name attribute for contact
1633     *    (Array)  groups - array of groups contact is member of
1634     */
1635   
1636        this.addContact = function(jid, subscription, name, groups )
1637        {
1638        if( subscription !== "remove" )
1639        {
1640                var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
1641                var jid_lower   = jid.toLowerCase();
1642       
1643                        if ( this.roster[jid_lower] )
1644                        {
1645                    this.roster[jid_lower]['contact'] = contact;
1646                }
1647                        else
1648                        {
1649                    this.roster[jid_lower] = {contact:contact};
1650                }
1651
1652                        groups = groups ? groups : [''];
1653               
1654                        for ( var g = 0; g < groups.length; g++ )
1655                        {
1656                                if ( !this.groups[groups[g]] )
1657                                {
1658                        this.groups[groups[g]] = {};
1659                    }
1660                   
1661                                this.groups[groups[g]][jid_lower] = jid_lower;
1662                }
1663        }
1664        else
1665        {
1666                this.removeContact(jid);
1667        }
1668    }
1669   
1670    /** Function: getContact
1671     *
1672     *  Returns contact entry for given jid
1673     *
1674     *  Parameter: (String) jid - jid to return
1675     */
1676     
1677    this.getContact = function(jid)
1678        {
1679        if (this.roster[jid.toLowerCase()])
1680                {
1681            return this.roster[jid.toLowerCase()]['contact'];
1682        }
1683    }
1684
1685   /** Function: getPresence
1686        *
1687        *  Returns best presence for given jid as Array(resource, priority, show,
1688        *  status)
1689        *
1690        *  Parameter: (String) fulljid - jid to return best presence for
1691        */
1692         
1693        this.getPresence = function(fulljid)
1694        {
1695                var jid = Strophe.getBareJidFromJid(fulljid);
1696                var current = null;
1697                   
1698                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
1699                {
1700                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
1701                        {
1702                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
1703                                continue;
1704                       
1705                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1706                                if (current == null)
1707                                {
1708                                        current = presence
1709                                }
1710                                else
1711                                {
1712                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1713                                        || presence['show'] == "available") || (current['show'] != "chat" ||
1714                                        current['show'] != "available")))
1715                                        {
1716                                                current = presence
1717                                        }
1718                                }
1719                        }
1720                }
1721                return current;
1722        }
1723
1724        /** Function: groupHasChanges
1725         *
1726         *  Returns true if current group has members in this.changes
1727         *
1728         *  Parameters:
1729         *    (String) group - name of group to check
1730         */
1731         
1732        this.groupHasChanges = function(group)
1733        {
1734                for (var c = 0; c < this.changes.length; c++)
1735                {
1736                        if (this.groups[group][this.changes[c]])
1737                        {
1738                                return true;
1739                        }
1740                }
1741                return false;
1742        }
1743       
1744        /** Function removeContact
1745         *
1746         * Parameters
1747         *       (String) jid           
1748         */
1749         
1750         this.removeContact = function(jid)
1751         {
1752                if( this.roster[ jid ] )
1753                {
1754                        var groups = this.roster[ jid ].contact.groups;
1755                       
1756                        if( groups )
1757                        {
1758                                for ( var i = 0; i < groups.length; i++ )
1759                                {
1760                                        delete this.groups[ groups[ i ] ][ jid ];
1761                                }
1762       
1763                                for ( var i = 0; i < groups.length; i++ )
1764                                {
1765                                        var contacts = 0;
1766                                        for ( var contact in this.groups[ groups[ i ] ] )
1767                                        {
1768                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
1769                                                continue;
1770                                       
1771                                                contacts++;
1772                                        }
1773               
1774                                        if ( ! contacts )
1775                                                delete this.groups[ groups[ i ] ];
1776                                }
1777                        }
1778       
1779                        // Delete Object roster
1780                        if( this.roster[jid] )
1781                                delete this.roster[jid];
1782                }
1783         }
1784         
1785    /** Function: setPresence
1786     *
1787     *  Sets presence
1788     *
1789     *  Parameters:
1790     *    (String) fulljid: full jid with presence
1791     *    (Integer) priority: priority attribute from presence
1792     *    (String) show: show attribute from presence
1793     *    (String) status: status attribute from presence
1794     */
1795   
1796        this.setPresence = function(fulljid, priority, show, status)
1797        {
1798                var barejid             = Strophe.getBareJidFromJid(fulljid);
1799        var resource    = Strophe.getResourceFromJid(fulljid);
1800        var jid_lower   = barejid.toLowerCase();
1801       
1802                if( show != 'unavailable')
1803                {
1804            if (!this.roster[jid_lower])
1805                        {
1806                this.addContact(barejid, 'not-in-roster');
1807            }
1808            var presence =
1809                        {
1810                resource:resource, priority:priority, show:show, status:status
1811            }
1812           
1813                        if (!this.roster[jid_lower]['presence'])
1814                        {
1815                this.roster[jid_lower]['presence'] = {};
1816            }
1817            this.roster[jid_lower]['presence'][resource] = presence;
1818        }
1819                else if (this.roster[jid_lower] && this.roster[jid_lower]['presence'] && this.roster[jid_lower]['presence'][resource])
1820                {
1821            delete this.roster[jid_lower]['presence'][resource];
1822        }
1823       
1824                this.addChange(jid_lower);
1825    }
1826
1827        /** Fuction: save
1828         *
1829         *  Saves roster data to JSON store
1830         */
1831       
1832        this.save = function()
1833        {
1834                if (TrophyIM.JSONStore.store_working)
1835                {
1836                        TrophyIM.JSONStore.setData({roster:this.roster,
1837                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
1838                        chat_history:TrophyIM.chatHistory});
1839                }
1840        }
1841
1842}
1843/** Class: TrophyIMJSONStore
1844 *
1845 *
1846 *  This object is the mechanism by which TrophyIM stores and retrieves its
1847 *  variables from the url provided by TROPHYIM_JSON_STORE
1848 *
1849 */
1850function TrophyIMJSONStore() {
1851    this.store_working = false;
1852    /** Function _newXHR
1853     *
1854     *  Set up new cross-browser xmlhttprequest object
1855     *
1856     *  Parameters:
1857     *    (function) handler = what to set onreadystatechange to
1858     */
1859     this._newXHR = function (handler) {
1860        var xhr = null;
1861        if (window.XMLHttpRequest) {
1862            xhr = new XMLHttpRequest();
1863            if (xhr.overrideMimeType) {
1864            xhr.overrideMimeType("text/xml");
1865            }
1866        } else if (window.ActiveXObject) {
1867            xhr = new ActiveXObject("Microsoft.XMLHTTP");
1868        }
1869        return xhr;
1870    }
1871    /** Function getData
1872     *  Gets data from JSONStore
1873     *
1874     *  Parameters:
1875     *    (Array) vars = Variables to get from JSON store
1876     *
1877     *  Returns:
1878     *    Object with variables indexed by names given in parameter 'vars'
1879     */
1880    this.getData = function(vars) {
1881        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1882            Strophe.debug("Retrieving JSONStore data");
1883            var xhr = this._newXHR();
1884            var getdata = "get=" + vars.join(",");
1885            try {
1886                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1887            } catch (e) {
1888                Strophe.error("JSONStore open failed.");
1889                return false;
1890            }
1891            xhr.setRequestHeader('Content-type',
1892            'application/x-www-form-urlencoded');
1893            xhr.setRequestHeader('Content-length', getdata.length);
1894            xhr.send(getdata);
1895            if (xhr.readyState == 4 && xhr.status == 200) {
1896                try {
1897                    var dataObj = JSON.parse(xhr.responseText);
1898                    return this.emptyFix(dataObj);
1899                } catch(e) {
1900                    Strophe.error("Could not parse JSONStore response" +
1901                    xhr.responseText);
1902                    return false;
1903                }
1904            } else {
1905                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1906                return false;
1907            }
1908        }
1909    }
1910    /** Function emptyFix
1911     *    Fix for bugs in external JSON implementations such as
1912     *    http://bugs.php.net/bug.php?id=41504.
1913     *    A.K.A. Don't use PHP, people.
1914     */
1915    this.emptyFix = function(obj) {
1916        if (typeof(obj) == "object") {
1917            for (var i in obj) {
1918                        if ( obj[i].constructor == Function )
1919                                continue;
1920                       
1921                if (i == '_empty_') {
1922                    obj[""] = this.emptyFix(obj['_empty_']);
1923                    delete obj['_empty_'];
1924                } else {
1925                    obj[i] = this.emptyFix(obj[i]);
1926                }
1927            }
1928        }
1929        return obj
1930    }
1931    /** Function delData
1932     *    Deletes data from JSONStore
1933     *
1934     *  Parameters:
1935     *    (Array) vars  = Variables to delete from JSON store
1936     *
1937     *  Returns:
1938     *    Status of delete attempt.
1939     */
1940    this.delData = function(vars) {
1941        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1942            Strophe.debug("Retrieving JSONStore data");
1943            var xhr = this._newXHR();
1944            var deldata = "del=" + vars.join(",");
1945            try {
1946                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1947            } catch (e) {
1948                Strophe.error("JSONStore open failed.");
1949                return false;
1950            }
1951            xhr.setRequestHeader('Content-type',
1952            'application/x-www-form-urlencoded');
1953            xhr.setRequestHeader('Content-length', deldata.length);
1954            xhr.send(deldata);
1955            if (xhr.readyState == 4 && xhr.status == 200) {
1956                try {
1957                    var dataObj = JSON.parse(xhr.responseText);
1958                    return dataObj;
1959                } catch(e) {
1960                    Strophe.error("Could not parse JSONStore response");
1961                    return false;
1962                }
1963            } else {
1964                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1965                return false;
1966            }
1967        }
1968    }
1969    /** Function setData
1970     *    Stores data in JSONStore, overwriting values if they exist
1971     *
1972     *  Parameters:
1973     *    (Object) vars : Object containing named vars to store ({name: value,
1974     *    othername: othervalue})
1975     *
1976     *  Returns:
1977     *    Status of storage attempt
1978     */
1979    this.setData = function(vars)
1980    {
1981        if ( typeof(TROPHYIM_JSON_STORE) != undefined )
1982        {
1983            var senddata = "set=" + JSON.stringify(vars);
1984            var xhr = this._newXHR();
1985            try
1986            {
1987                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1988            }
1989            catch (e)
1990            {
1991                Strophe.error("JSONStore open failed.");
1992                return false;
1993            }
1994            xhr.setRequestHeader('Content-type',
1995            'application/x-www-form-urlencoded');
1996            xhr.setRequestHeader('Content-length', senddata.length);
1997            xhr.send(senddata);
1998            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
1999            "OK") {
2000                return true;
2001            } else {
2002                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2003                return false;
2004            }
2005        }
2006    }
2007   
2008    var testData = true;
2009   
2010    if (this.setData({testData:testData})) {
2011        var testResult = this.getData(['testData']);
2012        if (testResult && testResult['testData'] == true) {
2013            this.store_working = true;
2014        }
2015    }
2016}
2017/** Constants: Node types
2018 *
2019 * Implementations of constants that IE doesn't have, but we need.
2020 */
2021if (document.ELEMENT_NODE == null) {
2022    document.ELEMENT_NODE = 1;
2023    document.ATTRIBUTE_NODE = 2;
2024    document.TEXT_NODE = 3;
2025    document.CDATA_SECTION_NODE = 4;
2026    document.ENTITY_REFERENCE_NODE = 5;
2027    document.ENTITY_NODE = 6;
2028    document.PROCESSING_INSTRUCTION_NODE = 7;
2029    document.COMMENT_NODE = 8;
2030    document.DOCUMENT_NODE = 9;
2031    document.DOCUMENT_TYPE_NODE = 10;
2032    document.DOCUMENT_FRAGMENT_NODE = 11;
2033    document.NOTATION_NODE = 12;
2034}
2035
2036/** Function: importNode
2037 *
2038 *  document.importNode implementation for IE, which doesn't have importNode
2039 *
2040 *  Parameters:
2041 *    (Object) node - dom object
2042 *    (Boolean) allChildren - import node's children too
2043 */
2044if (!document.importNode) {
2045    document.importNode = function(node, allChildren) {
2046        switch (node.nodeType) {
2047            case document.ELEMENT_NODE:
2048                var newNode = document.createElement(node.nodeName);
2049                if (node.attributes && node.attributes.length > 0) {
2050                    for(var i = 0; i < node.attributes.length; i++) {
2051                        newNode.setAttribute(node.attributes[i].nodeName,
2052                        node.getAttribute(node.attributes[i].nodeName));
2053                    }
2054                }
2055                if (allChildren && node.childNodes &&
2056                node.childNodes.length > 0) {
2057                    for (var i = 0; i < node.childNodes.length; i++) {
2058                        newNode.appendChild(document.importNode(
2059                        node.childNodes[i], allChildren));
2060                    }
2061                }
2062                return newNode;
2063                break;
2064            case document.TEXT_NODE:
2065            case document.CDATA_SECTION_NODE:
2066            case document.COMMENT_NODE:
2067                return document.createTextNode(node.nodeValue);
2068                break;
2069        }
2070    };
2071}
2072
2073/**
2074 *
2075 * Bootstrap self into window.onload and window.onunload
2076 */
2077
2078var oldonunload = window.onunload;
2079
2080window.onunload = function()
2081{
2082        if( oldonunload )
2083        {
2084        oldonunload();
2085    }
2086       
2087        TrophyIM.setPresence('unavailable');
2088}
Note: See TracBrowser for help on using the repository browser.