source: trunk/jmessenger/js/trophyim.js @ 2961

Revision 2961, 58.6 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #1114 - Erro na remocao de contatos do IM ( modulo sem java ).

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