source: trunk/jabberit_messenger/jmessenger/js/trophyim.js @ 3082

Revision 3082, 61.0 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #1091 - Implementado a busca de salas para bate-papo no novo modulo Expresso messenger XEP-0045-MUC.

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