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

Revision 2787, 56.8 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Implementado os popups para as janelas de conversa e somente para navegadores Firefox.

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