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

Revision 2836, 59.3 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Corrigindo o file enconding de UTF-8 para ISO-8859-1

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