source: trunk/jabberit_messenger/jmessenger/js/trophyim.js @ 3126

Revision 3126, 67.9 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #1091 - Implementado a busca de salas para bate-papo no novo modulo Expresso messenger XEP-0045-MUC.

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