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

Revision 2716, 54.8 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Implementado para mostrar a hora da mensagem e sua conversao para mensagens recebidas.

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