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

Revision 2821, 58.7 KB checked in by emmanuel.ferro, 14 years ago (diff)

Ticket #986 - [SERPRO] Implementacao da XEP-0085 - ok

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