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

Revision 2835, 59.3 KB checked in by emmanuel.ferro, 14 years ago (diff)

Ticket #986 - [SERPRO] - Corrigido timer que limpa a msg de estado de chat

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