source: branches/2.2/jabberit_messenger/jmessenger/js/trophyim.js @ 3122

Revision 3122, 67.4 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                setTimeout( function()
1103                {
1104                        _winBuild('window_chat_room_' + jidChatRoom, 'remove');
1105                       
1106                }, 500 );
1107               
1108        });
1109       
1110                loadscript.configEvents( _textarea, 'onkeyup', function( e )
1111                {
1112                        if ( e.keyCode == 13 )
1113                        {
1114                                _send_message( );
1115                        }
1116                });       
1117       
1118        var winChatRoom =
1119        {
1120                         id_window              : "window_chat_room_" + arguments[0],
1121                         barejid                : jidChatRoom,
1122                         width                  : 500,
1123                         height                 : 450,
1124                         top                    : TrophyIM.posWindow.top,
1125                         left                   : TrophyIM.posWindow.left,
1126                         draggable              : true,
1127                         visible                : "display",
1128                         resizable              : true,
1129                         zindex                 : loadscript.getZIndex(),
1130                         title                  : titleWindow,
1131                         closeAction    : "hidden",
1132                         content                : _content     
1133        }
1134       
1135        _win = _winBuild(winChatRoom);
1136       
1137        return ( _messages = _win.content( ).firstChild );
1138       
1139    },
1140   
1141        /** Function addContacts
1142         *
1143         *  Parameters:
1144         *              (string) jidFrom         
1145         *      (string) jidTo
1146         *              (string) name
1147         *              (string) group   
1148         */
1149       
1150        addContact : function( jidTo, name, group )
1151        {
1152                // Add Contact
1153        var _id = TrophyIM.connection.getUniqueId('add');
1154                var newContact = $iq({type: 'set', id: _id });
1155                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1156                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
1157                        newContact = newContact.c('group').t(group).tree();
1158
1159                TrophyIM.connection.send(newContact);
1160        },
1161
1162    /** Function: add
1163     *
1164     *  Parameters:
1165     *    (string) msg - the message to add
1166     *    (string) jid - the jid of chat box to add the message to.
1167     */
1168       
1169    addMessage : function( chatBox, jid, msg )
1170    {
1171        // Get Smiles
1172        msg.msg = loadscript.getSmiles( msg.msg );
1173 
1174        var messageDiv  = document.createElement("div");
1175                messageDiv.style.margin = "3px 0px 1em 3px";
1176        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
1177               
1178        chatBox.appendChild(messageDiv);
1179        chatBox.scrollTop = chatBox.scrollHeight;
1180    },
1181       
1182    /** Function : renameContact
1183     *
1184     *
1185     */
1186   
1187    renameContact : function( jid )
1188    {
1189        // Name
1190        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
1191
1192                if(( name = prompt(i18n.ASK_NEW_NAME_QUESTION + name + "!", name )))
1193                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1194                                name = "";
1195
1196                if( name == null || name == "")
1197                        name = "";
1198               
1199        var jidTo = jid
1200        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
1201        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1202       
1203        TrophyIM.addContact( jidTo, name, group );
1204       
1205        document.getElementById('itenContact_' + jid ).innerHTML = name;
1206    },
1207   
1208    /** Function : renameGroup
1209     *
1210     *
1211     */
1212
1213    renameGroup : function( jid )
1214    {
1215        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1216        var presence    = TrophyIM.rosterObj.roster[jid].presence;
1217       
1218                // Group
1219                if(( group = prompt( i18n.ASK_NEW_GROUP_QUESTION, group )))
1220                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1221                                group = "";
1222
1223                if( group == null || group == "")
1224                        group = "";
1225
1226        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
1227        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
1228                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
1229
1230                TrophyIM.rosterObj.removeContact( jid );
1231               
1232                TrophyIM.addContact( jidTo, name, group );
1233       
1234                document.getElementById("JabberIMRoster").innerHTML = "";
1235               
1236        TrophyIM.renderRoster();
1237       
1238        setTimeout(function()
1239        {
1240                for( var i in presence )
1241                {
1242                        if ( presence[ i ].constructor == Function )
1243                                continue;
1244                               
1245                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
1246                }
1247        },500);
1248    },
1249
1250    /** Function createChatRooms
1251     *
1252     *
1253     */
1254   
1255    createChatRooms : function()
1256    {
1257        var nickName     = document.getElementById('nickName_chatRoom_jabberit').value;
1258        var nameChatRoom = document.getElementById('name_ChatRoom_jabberit').value;
1259       
1260        var _from               = Base64.decode( loadscript.getUserCurrent().jid ) + TROPHYIM_RESOURCE;
1261                var _to                 = escape( nameChatRoom ) + "@" + TROPHYIM_CHATROOM + "/" + nickName ;
1262                var new_room    = $pres( {from: _from, to: _to } ).c( "x", { xmlns: Strophe.NS.MUC } );
1263
1264                TrophyIM.connection.send( new_room.tree() );
1265    },
1266   
1267    /** Function : joinRoom
1268     *
1269     *
1270     */
1271   
1272    joinChatRoom : function( roomName )
1273    {
1274        var presence = $pres( {from: TrophyIM.connection.jid, to: roomName} ).c("x",{xmlns: Strophe.NS.MUC});
1275       
1276                TrophyIM.connection.send( presence );
1277    },
1278   
1279    /** Function : Leave Chat Room
1280     *
1281     *
1282     */
1283   
1284    leaveChatRoom : function( roomName )
1285    {
1286        var room_nick   = roomName;
1287       
1288        var presenceid  = TrophyIM.connection.getUniqueId();
1289       
1290        var presence    = $pres( {type: "unavailable", id: presenceid, from: TrophyIM.connection.jid, to: room_nick} ).c("x",{xmlns: Strophe.NS.MUC});
1291       
1292        TrophyIM.connection.send( presence );       
1293    },
1294   
1295    /** Function : getlistRooms
1296     *
1297     *
1298     */
1299   
1300    getListRooms : function()
1301    {
1302        var _error_return = function(element)
1303        {
1304                alert( " ERROR : " + element );
1305        };
1306       
1307                var iq = $iq({to: "conference.im.pr.gov.br", type: "get"}).c("query",{xmlns: Strophe.NS.DISCO_ITEMS});                 
1308               
1309        TrophyIM.connection.sendIQ( iq, loadscript.listRooms, _error_return, 500 );             
1310    },
1311   
1312    /** Function: removeContact
1313     *
1314     *  Parameters:
1315     *          (string) jidTo
1316     */
1317   
1318    removeContact : function( jidTo )
1319    {
1320        var divItenContact       = null;
1321
1322        if( ( divItenContact = document.getElementById('itenContact_' + jidTo )))
1323        {       
1324                // Remove Contact
1325                var _id = TrophyIM.connection.getUniqueId();   
1326                var delContact  = $iq({type: 'set', id: _id})
1327                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1328                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
1329
1330                TrophyIM.connection.send( delContact );
1331               
1332                        loadscript.removeElement( document.getElementById('itenContactNotification_' + jidTo ) );
1333               
1334                var spanShow = document.getElementById('span_show_itenContact_' + jidTo )
1335                        spanShow.parentNode.removeChild(spanShow);
1336               
1337                loadscript.removeGroup( divItenContact.parentNode );
1338               
1339                divItenContact.parentNode.removeChild(divItenContact);
1340        }
1341    },
1342   
1343    /** Function: renderRoster
1344     *
1345     *  Renders roster, looking only for jids flagged by setPresence as having
1346     *  changed.
1347     */
1348   
1349        renderRoster : function()
1350        {
1351                var roster_div = document.getElementById('JabberIMRoster');
1352               
1353                if( roster_div )
1354                {
1355                        var users = new Array();
1356                       
1357                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1358                       
1359                        if( loading_gif.style.display == "block" )
1360                                loading_gif.style.display = "none";
1361                               
1362                        for( var user in TrophyIM.rosterObj.roster )
1363                        {
1364                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
1365                                        continue;
1366
1367                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
1368                        }
1369
1370                        users.sort();
1371                       
1372                        var groups              = new Array();
1373                        var flagGeral   = false;
1374                       
1375                        for (var group in TrophyIM.rosterObj.groups)
1376                        {
1377                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
1378                                        continue;
1379                               
1380                                if( group )
1381                                        groups[groups.length] = group;
1382                               
1383                                if( group == "Geral" )
1384                                        flagGeral = true;
1385            }
1386           
1387                        if( !flagGeral && users.length > 0 )
1388                                groups[groups.length] = "Geral";
1389                               
1390                        groups.sort();
1391                       
1392                        for ( var i = 0; i < groups.length; i++ )
1393                        {
1394                                TrophyIM.renderGroups( groups[i] , roster_div );       
1395                        }
1396                       
1397                        TrophyIM.renderItensGroup( users, roster_div );
1398                }
1399                       
1400                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
1401        },
1402       
1403    /** Function: renderGroups
1404     *
1405     *
1406     */
1407       
1408        renderGroups: function( nameGroup, element )
1409        {
1410                var _addGroup = function()
1411                {
1412                        var _nameGroup  = nameGroup;
1413                        var _element    = element;
1414
1415                        var paramsGroup =
1416                        {
1417                                'nameGroup'     : _nameGroup,
1418                                'path_jabberit' : path_jabberit
1419                        }
1420                       
1421                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
1422                }
1423
1424                if( !element.hasChildNodes() )
1425                {
1426                        _addGroup();
1427                }
1428                else
1429                {
1430                        var _NodeChild  = element.firstChild;
1431                        var flagAdd             = false;
1432                       
1433                        while( _NodeChild )
1434                        {
1435                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1436                                {
1437                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
1438                                        {
1439                                                flagAdd = true;
1440                                        }
1441                                }
1442                               
1443                                _NodeChild = _NodeChild.nextSibling;
1444                        }
1445
1446                        if( !flagAdd )
1447                        {
1448                                _addGroup();
1449                        }
1450                }
1451        },
1452
1453    /** Function: renderItensGroup
1454     *
1455     *
1456     */
1457
1458        renderItensGroup : function( users, element )
1459        {
1460                var addItem = function()
1461                {
1462                        if( arguments.length > 0 )
1463                        {
1464                                // Get Arguments
1465                                var objContact  = arguments[0];
1466                                var group               = arguments[1];
1467                                var element             = arguments[2];
1468                                var showOffline = loadscript.getShowContactsOffline();
1469                               
1470                                // Presence e Status
1471                                var presence            = "unavailable";
1472                                var status                      = "";
1473                                var statusColor         = "black";
1474                                var statusDisplay       = "none";
1475                               
1476                                var _resource   = "";
1477                               
1478                                // Set Presence
1479                                var _presence = function(objContact)
1480                                {
1481                                        if (objContact.presence)
1482                                        {
1483                                                for (var resource in objContact.presence)
1484                                                {
1485                                                        if ( objContact.presence[resource].constructor == Function )
1486                                                                continue;
1487
1488                                                        if( objContact.presence[resource].show != 'invisible' )
1489                                                                presence = objContact.presence[resource].show;
1490
1491                                                        if( objContact.contact.subscription != "both")
1492                                                                presence = 'subscription';
1493                                                       
1494                                                        if( objContact.presence[resource].status )
1495                                                        {
1496                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1497                                                                statusDisplay   = "block";
1498                                                        }
1499                                                }
1500                                        }
1501                                };
1502                               
1503                                // Set Subscription
1504                                var _subscription = function( objContact )
1505                                {
1506                                        if( objContact.contact.subscription != "both" )
1507                                        {
1508                                                switch( objContact.contact.subscription )
1509                                                {
1510                                                        case "none" :
1511                                                               
1512                                                                status          = " (( " + i18n.ASK_FOR_AUTH  + " )) ";
1513                                                                statusColor     = "red";
1514                                                                break;
1515       
1516                                                        case "to" :
1517                                                               
1518                                                                status          = " (( " + i18n.CONTACT_ASK_FOR_AUTH  + " )) ";
1519                                                                statusColor     = "orange";
1520                                                                break;
1521       
1522                                                        case "from" :
1523                                                               
1524                                                                status          = " (( " + i18n.AUTHORIZED + " )) ";
1525                                                                statusColor = "green";
1526                                                                break;
1527                                                               
1528                                                        case "subscribe" :
1529                                                               
1530                                                                status          = " (( " + i18n.AUTH_SENT  + " )) ";
1531                                                                statusColor     = "red";       
1532                                                                break;
1533
1534                                                        case "not-in-roster" :
1535                                                               
1536                                                                status          = " (( " + i18n.ASK_FOR_AUTH_QUESTION  + " )) ";
1537                                                                statusColor     = "orange";     
1538                                                                break;
1539                                                               
1540                                                        default :
1541                                                               
1542                                                                break;
1543                                                }
1544
1545                                                statusDisplay = "block";
1546                                        }
1547                                };
1548
1549                                if( objContact.contact.subscription != "remove")
1550                                {
1551                                        var itensJid    = document.getElementById( "itenContact_" + objContact.contact.jid );
1552                                       
1553                                        if( itensJid == null )
1554                                        {
1555                                                // Name
1556                                                var nameContact = "";                                   
1557                                               
1558                                                if ( objContact.contact.name )
1559                                                        nameContact = objContact.contact.name;
1560                                                else
1561                                                {
1562                                                        nameContact = objContact.contact.jid;
1563                                                        nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1564                                                }
1565                                               
1566                                                // Get Presence
1567                                                _presence(objContact);
1568                                               
1569                                                var paramsContact =
1570                                                {
1571                                                        divDisplay              : "block",
1572                                                        id                              : 'itenContact_' + objContact.contact.jid ,
1573                                                        jid                             : objContact.contact.jid,
1574                                                        nameContact     : nameContact,
1575                                                        path_jabberit   : path_jabberit,
1576                                                        presence                : presence,
1577                                                        spanDisplay             : statusDisplay,
1578                                                        status                  : status,
1579                                                        statusColor             : "black",
1580                                                        subscription    : objContact.contact.subscription,
1581                                                        resource                : _resource
1582                                                }
1583                                               
1584                                                // Get Authorization
1585                                                _subscription( objContact );
1586                                               
1587                                                if( group != "")
1588                                                {
1589                                                        var _NodeChild          = element.firstChild;
1590                                                       
1591                                                        while( _NodeChild )
1592                                                        {
1593                                                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1594                                                                {
1595                                                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1596                                                                        {
1597                                                                                _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1598                                                                        }
1599                                                                }
1600       
1601                                                                _NodeChild = _NodeChild.nextSibling;
1602                                                        }
1603                                                }       
1604                                        }
1605                                        else
1606                                        {
1607                                                // Get Presence
1608                                                _presence(objContact);
1609       
1610                                                var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1611                                                        is_open = is_open.indexOf("arrow_down.gif");
1612       
1613                                                // Get Authorization
1614                                                _subscription( objContact );
1615                                               
1616                                                // Set subscription
1617                                                itensJid.setAttribute('subscription', objContact.contact.subscription );
1618                                               
1619                                                with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ) )
1620                                                {
1621                                                        if( presence == "unavailable" && !showOffline )
1622                                                        {
1623                                                                style.display = "none";
1624                                                        }
1625                                                        else
1626                                                        {
1627                                                                if( is_open > 0 )
1628                                                                {
1629                                                                        style.display   = statusDisplay;
1630                                                                        style.color             = statusColor;
1631                                                                        innerHTML               = status;
1632                                                                }
1633                                                        }
1634                                                }
1635                                               
1636                                                if( presence == "unavailable" && !showOffline )
1637                                                {
1638                                                        itensJid.style.display = "none";
1639                                                }
1640                                                else
1641                                                {
1642                                                        if( is_open > 0 )
1643                                                        {
1644                                                                itensJid.style.display = "block";
1645                                                        }
1646                                                }
1647                                               
1648                                                itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1649                                        }
1650       
1651                                        // Contact OffLine
1652                                        if( !objContact.presence && !showOffline )
1653                                        {
1654                                                if( objContact.contact.subscription != "remove" )
1655                                                {
1656                                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ))
1657                                                        {
1658                                                                style.display   = "none";
1659                                                        }
1660               
1661                                                        with ( document.getElementById('itenContact_' + objContact.contact.jid ) )
1662                                                        {
1663                                                                style.display   = "none";
1664                                                        }
1665                                                }
1666                                        }
1667                                }
1668                        }
1669                };
1670               
1671                var flag = false;
1672               
1673                for( var i = 0 ; i < users.length; i++ )
1674                {
1675                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode( loadscript.getUserCurrent().jid) )
1676                        {
1677                                var _subscription = TrophyIM.rosterObj.roster[users[i]].contact.subscription;
1678                               
1679                                if( _subscription === "to" )
1680                                {
1681                                        flag = true;
1682                                }
1683                               
1684                                if(  _subscription === "not-in-roster")
1685                                {
1686                                        flag = true;
1687                                }
1688                               
1689                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1690                                {
1691                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1692                                       
1693                                        if( groups.length > 0 )
1694                                        {
1695                                                for( var j = 0; j < groups.length; j++ )
1696                                                {
1697                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element );
1698                                                }
1699                                        }
1700                                        else
1701                                        {
1702                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1703                                        }
1704                                }
1705                                else
1706                                {
1707                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1708                                }
1709                        }
1710                }
1711               
1712                if( flag )
1713                {
1714                        if ( TrophyIM.controll.notificationNewUsers == 0 )
1715                        {
1716                                loadscript.enabledNotificationNewUsers();
1717                                TrophyIM.controll.notificationNewUsers++;
1718                        }
1719                }
1720                else
1721                {
1722                        loadscript.disabledNotificationNewUsers();
1723                        TrophyIM.controll.notificationNewUsers = 0;
1724                }
1725        },
1726
1727    /** Function: rosterClick
1728     *
1729     *  Handles actions when a roster item is clicked
1730     */
1731   
1732        rosterClick : function(fulljid)
1733        {
1734        TrophyIM.makeChat(fulljid);
1735    },
1736
1737        /** Function SetAutorization
1738         *
1739         */
1740
1741        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1742        {
1743        var _id = TrophyIM.connection.getUniqueId();
1744       
1745        TrophyIM.connection.send($pres( ).attrs({ from: jidFrom, to: jidTo, type: _typeSubscription, id: _id }).tree());
1746        },
1747
1748        /** Function: setPresence
1749     *
1750     */
1751
1752        setPresence : function( _type )
1753        {
1754                var presence_chatRoom = "";
1755               
1756                if( _type != 'status')
1757                {
1758                        if( _type == "unavailable" &&  TrophyIM.statusConn.connected )
1759                        {
1760                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1761                               
1762                                if( TrophyIM._timeOut.renderRoster != null )
1763                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1764                               
1765                                if( TrophyIM.statusConn.connected )
1766                                        TrophyIM.connection.send($pres({type : _type}).tree());
1767                               
1768                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1769                        {
1770                                if( TrophyIM.connection._requests[i] )
1771                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1772                        }
1773                               
1774                                TrophyIM.logout();
1775                               
1776                        loadscript.clrAllContacts();
1777                       
1778                        delete TrophyIM.rosterObj.roster;
1779                        delete TrophyIM.rosterObj.groups;
1780                       
1781                        setTimeout(function()
1782                        {
1783                                        if( loading_gif.style.display == "block" )
1784                                                loading_gif.style.display = "none";
1785                        }, 1000);
1786                        }
1787                        else
1788                        {
1789                                if( !TrophyIM.autoConnection.connect )
1790                                {
1791                                        TrophyIM.autoConnection.connect = true;
1792                                        TrophyIM.load();
1793                                }
1794                                else
1795                                {
1796                                        if( TrophyIM.statusConn.connected )
1797                                        {
1798                                                if( loadscript.getStatusMessage() != "" )
1799                                                {
1800                                                        var _presence = $pres( );
1801                                                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1802                                                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1803                                                       
1804                                                        TrophyIM.connection.send( _presence.tree() );
1805                                                       
1806                                                        presence_chatRoom = _type;
1807                                                }
1808                                                else
1809                                                {
1810                                                        TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1811                                                       
1812                                                        presence_chatRoom = _type;
1813                                                }
1814                                        }
1815                                }
1816                        }
1817                }
1818                else
1819                {
1820                        var _show       = "available";
1821                        var _status     = "";
1822                       
1823                        if( arguments.length < 2 )
1824                        {
1825                                if( loadscript.getStatusMessage() != "" )
1826                                        _status = prompt(i18n.TYPE_YOUR_MSG, loadscript.getStatusMessage());
1827                                else
1828                                        _status = prompt(i18n.TYPE_YOUR_MSG);
1829                               
1830                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1831                               
1832                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1833                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1834                        }
1835                        else
1836                        {
1837                                _status = arguments[1];
1838                        }
1839
1840                        for( var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1841                        {
1842                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1843                                continue;
1844                       
1845                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1846                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1847                        }
1848
1849                        if ( TrophyIM.statusConn.connected )
1850                        {
1851                                var _presence = $pres( );
1852                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1853                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1854                               
1855                                TrophyIM.connection.send( _presence.tree() );
1856                               
1857                                presence_chatRoom = _show;
1858                        }
1859                }
1860               
1861                // Send Presence Chat Room
1862                if( TrophyIM.activeChatRoom.name.length > 0 )
1863                {
1864                        for( var i in TrophyIM.activeChatRoom.name )
1865                        {
1866                                TrophyIM.connection.send($pres( { to : TrophyIM.activeChatRoom.name[i] } ).c('show').t( presence_chatRoom ) );
1867                        }
1868                }
1869
1870        },
1871       
1872        /** Function: sendMessage
1873     *
1874     *  Send message from chat input to user
1875     */
1876     
1877    sendMessage : function()
1878    {
1879                if (arguments.length > 0)
1880                {
1881                        var jidTo = arguments[0];
1882                        var message_input = arguments[1];
1883                       
1884                       
1885                        message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g, "");
1886                       
1887                        if (message_input != "") {
1888                       
1889                                // Send Message
1890                                var newMessage = $msg({
1891                                        to: jidTo,
1892                                        from: TrophyIM.connection.jid,
1893                                        type: 'chat'
1894                                });
1895                                newMessage = newMessage.c('body').t(message_input);
1896                                newMessage.up();
1897                                newMessage = newMessage.c('active').attrs({
1898                                        xmlns: 'http://jabber.org/protocol/chatstates'
1899                                });
1900                                // Send Message
1901                                TrophyIM.connection.send(newMessage.tree());
1902                               
1903                                return true;
1904                        }
1905                }
1906               
1907                return false;
1908    },
1909
1910        /** Function: sendMessage
1911    *
1912    *  Send message to ChatRoom
1913    */
1914   
1915    sendMessageChatRoom : function( room )
1916    {
1917        if( arguments.length > 0 )
1918        {
1919                var room_nick   = arguments[0];
1920                var message             = arguments[1];
1921                var msgid               = TrophyIM.connection.getUniqueId();
1922                var msg                 = $msg({to: room_nick, type: "groupchat", id: msgid}).c("body",{xmlns: Strophe.NS.CLIENT}).t(message);
1923               
1924                msg.up();//.c("x", {xmlns: "jabber:x:event"}).c("composing");
1925               
1926                TrophyIM.connection.send(msg);
1927               
1928                return true;
1929        }
1930    },
1931   
1932        /** Function: sendContentMessage
1933     *
1934     *  Send a content message from chat input to user
1935     */
1936        sendContentMessage : function()
1937    {
1938      if( arguments.length > 0 )
1939      {
1940         var jidTo = arguments[0];
1941         var state = arguments[1];
1942
1943         var newMessage = $msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'});
1944         newMessage = newMessage.c(state).attrs({xmlns : 'http://jabber.org/protocol/chatstates'});
1945         // Send content message
1946         TrophyIM.connection.send(newMessage.tree());
1947      }
1948    }
1949};
1950
1951/** Class: TrophyIMRoster
1952 *
1953 *
1954 *  This object stores the roster and presence info for the TrophyIMClient
1955 *
1956 *  roster[jid_lower]['contact']
1957 *  roster[jid_lower]['presence'][resource]
1958 */
1959function TrophyIMRoster()
1960{
1961    /** Constants: internal arrays
1962     *    (Object) roster - the actual roster/presence information
1963     *    (Object) groups - list of current groups in the roster
1964     *    (Array) changes - array of jids with presence changes
1965     */
1966    if (TrophyIM.JSONStore.store_working)
1967        {
1968        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1969        this.roster = (data['roster'] != null) ? data['roster'] : {};
1970        this.groups = (data['groups'] != null) ? data['groups'] : {};
1971    }
1972        else
1973        {
1974        this.roster = {};
1975        this.groups = {};
1976    }
1977    this.changes = new Array();
1978   
1979        if (TrophyIM.constants.stale_roster)
1980        {
1981        for (var jid in this.roster)
1982                {
1983                        this.changes[this.changes.length] = jid;
1984        }
1985    }
1986
1987        /** Function: addChange
1988         *
1989         *  Adds given jid to this.changes, keeping this.changes sorted and
1990         *  preventing duplicates.
1991         *
1992         *  Parameters
1993         *    (String) jid : jid to add to this.changes
1994         */
1995         
1996        this.addChange = function(jid)
1997        {
1998                for (var c = 0; c < this.changes.length; c++)
1999                {
2000                        if (this.changes[c] == jid)
2001                        {
2002                                return;
2003                        }
2004                }
2005               
2006                this.changes[this.changes.length] = jid;
2007               
2008                this.changes.sort();
2009        }
2010       
2011    /** Function: addContact
2012     *
2013     *  Adds given contact to roster
2014     *
2015     *  Parameters:
2016     *    (String) jid - bare jid
2017     *    (String) subscription - subscription attribute for contact
2018     *    (String) name - name attribute for contact
2019     *    (Array)  groups - array of groups contact is member of
2020     */
2021   
2022        this.addContact = function(jid, subscription, name, groups )
2023        {
2024                if( subscription === "remove" )
2025        {
2026                        this.removeContact(jid);
2027        }
2028        else
2029        {
2030                        var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
2031                var jid_lower   = jid.toLowerCase();
2032       
2033                        if ( this.roster[jid_lower] )
2034                        {
2035                    this.roster[jid_lower]['contact'] = contact;
2036                }
2037                        else
2038                        {
2039                    this.roster[jid_lower] = {contact:contact};
2040                }
2041
2042                        groups = groups ? groups : [''];
2043               
2044                        for ( var g = 0; g < groups.length; g++ )
2045                        {
2046                                if ( !this.groups[groups[g]] )
2047                                {
2048                        this.groups[groups[g]] = {};
2049                    }
2050                   
2051                                this.groups[groups[g]][jid_lower] = jid_lower;
2052                }
2053        }
2054    }
2055   
2056    /** Function: getContact
2057     *
2058     *  Returns contact entry for given jid
2059     *
2060     *  Parameter: (String) jid - jid to return
2061     */
2062     
2063    this.getContact = function(jid)
2064        {
2065        if (this.roster[jid.toLowerCase()])
2066                {
2067            return this.roster[jid.toLowerCase()]['contact'];
2068        }
2069    }
2070
2071   /** Function: getPresence
2072        *
2073        *  Returns best presence for given jid as Array(resource, priority, show,
2074        *  status)
2075        *
2076        *  Parameter: (String) fulljid - jid to return best presence for
2077        */
2078         
2079        this.getPresence = function(fulljid)
2080        {
2081                var jid = Strophe.getBareJidFromJid(fulljid);
2082                var current = null;
2083                   
2084                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
2085                {
2086                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
2087                        {
2088                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
2089                                continue;
2090                       
2091                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
2092                                if (current == null)
2093                                {
2094                                        current = presence
2095                                }
2096                                else
2097                                {
2098                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
2099                                        || presence['show'] == "available") || (current['show'] != "chat" ||
2100                                        current['show'] != "available")))
2101                                        {
2102                                                current = presence
2103                                        }
2104                                }
2105                        }
2106                }
2107                return current;
2108        }
2109
2110        /** Function: groupHasChanges
2111         *
2112         *  Returns true if current group has members in this.changes
2113         *
2114         *  Parameters:
2115         *    (String) group - name of group to check
2116         */
2117         
2118        this.groupHasChanges = function(group)
2119        {
2120                for (var c = 0; c < this.changes.length; c++)
2121                {
2122                        if (this.groups[group][this.changes[c]])
2123                        {
2124                                return true;
2125                        }
2126                }
2127                return false;
2128        }
2129       
2130        /** Function removeContact
2131         *
2132         * Parameters
2133         *       (String) jid           
2134         */
2135         
2136         this.removeContact = function(jid)
2137         {
2138                if( this.roster[ jid ] )
2139                {
2140                        var groups = this.roster[ jid ].contact.groups;
2141                       
2142                        if( groups )
2143                        {
2144                                for ( var i = 0; i < groups.length; i++ )
2145                                {
2146                                        delete this.groups[ groups[ i ] ][ jid ];
2147                                }
2148       
2149                                for ( var i = 0; i < groups.length; i++ )
2150                                {
2151                                        var contacts = 0;
2152                                        for ( var contact in this.groups[ groups[ i ] ] )
2153                                        {
2154                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
2155                                                continue;
2156                                       
2157                                                contacts++;
2158                                        }
2159               
2160                                        if ( ! contacts )
2161                                                delete this.groups[ groups[ i ] ];
2162                                }
2163                        }
2164       
2165                        // Delete Object roster
2166                        if( this.roster[jid] )
2167                                delete this.roster[jid];
2168                }
2169         }
2170         
2171    /** Function: setPresence
2172     *
2173     *  Sets presence
2174     *
2175     *  Parameters:
2176     *    (String) fulljid: full jid with presence
2177     *    (Integer) priority: priority attribute from presence
2178     *    (String) show: show attribute from presence
2179     *    (String) status: status attribute from presence
2180     */
2181   
2182        this.setPresence = function(fulljid, priority, show, status)
2183        {
2184                var barejid             = Strophe.getBareJidFromJid(fulljid);
2185        var resource    = Strophe.getResourceFromJid(fulljid);
2186        var jid_lower   = barejid.toLowerCase();
2187       
2188        if( show != 'unavailable' || show != 'error' )
2189                {
2190            if (!this.roster[jid_lower])
2191                        {
2192                this.addContact( barejid, 'not-in-roster' );
2193            }
2194           
2195            var presence =
2196                        {
2197                resource        : resource,
2198                priority        : priority,
2199                show            : show,
2200                status          : status
2201            }
2202           
2203                        if (!this.roster[jid_lower]['presence'])
2204                        {
2205                this.roster[jid_lower]['presence'] = {};
2206            }
2207           
2208            this.roster[jid_lower]['presence'][resource] = presence;   
2209                }
2210    }
2211
2212        /** Fuction: save
2213         *
2214         *  Saves roster data to JSON store
2215         */
2216       
2217        this.save = function()
2218        {
2219                if (TrophyIM.JSONStore.store_working)
2220                {
2221                        TrophyIM.JSONStore.setData({roster:this.roster,
2222                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
2223                        chat_history:TrophyIM.chatHistory});
2224                }
2225        }
2226
2227}
2228/** Class: TrophyIMJSONStore
2229 *
2230 *
2231 *  This object is the mechanism by which TrophyIM stores and retrieves its
2232 *  variables from the url provided by TROPHYIM_JSON_STORE
2233 *
2234 */
2235function TrophyIMJSONStore() {
2236    this.store_working = false;
2237    /** Function _newXHR
2238     *
2239     *  Set up new cross-browser xmlhttprequest object
2240     *
2241     *  Parameters:
2242     *    (function) handler = what to set onreadystatechange to
2243     */
2244     this._newXHR = function (handler) {
2245        var xhr = null;
2246        if (window.XMLHttpRequest) {
2247            xhr = new XMLHttpRequest();
2248            if (xhr.overrideMimeType) {
2249            xhr.overrideMimeType("text/xml");
2250            }
2251        } else if (window.ActiveXObject) {
2252            xhr = new ActiveXObject("Microsoft.XMLHTTP");
2253        }
2254        return xhr;
2255    }
2256    /** Function getData
2257     *  Gets data from JSONStore
2258     *
2259     *  Parameters:
2260     *    (Array) vars = Variables to get from JSON store
2261     *
2262     *  Returns:
2263     *    Object with variables indexed by names given in parameter 'vars'
2264     */
2265    this.getData = function(vars) {
2266        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2267            Strophe.debug("Retrieving JSONStore data");
2268            var xhr = this._newXHR();
2269            var getdata = "get=" + vars.join(",");
2270            try {
2271                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2272            } catch (e) {
2273                Strophe.error("JSONStore open failed.");
2274                return false;
2275            }
2276            xhr.setRequestHeader('Content-type',
2277            'application/x-www-form-urlencoded');
2278            xhr.setRequestHeader('Content-length', getdata.length);
2279            xhr.send(getdata);
2280            if (xhr.readyState == 4 && xhr.status == 200) {
2281                try {
2282                    var dataObj = JSON.parse(xhr.responseText);
2283                    return this.emptyFix(dataObj);
2284                } catch(e) {
2285                    Strophe.error("Could not parse JSONStore response" +
2286                    xhr.responseText);
2287                    return false;
2288                }
2289            } else {
2290                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2291                return false;
2292            }
2293        }
2294    }
2295    /** Function emptyFix
2296     *    Fix for bugs in external JSON implementations such as
2297     *    http://bugs.php.net/bug.php?id=41504.
2298     *    A.K.A. Don't use PHP, people.
2299     */
2300    this.emptyFix = function(obj) {
2301        if (typeof(obj) == "object") {
2302            for (var i in obj) {
2303                        if ( obj[i].constructor == Function )
2304                                continue;
2305                       
2306                if (i == '_empty_') {
2307                    obj[""] = this.emptyFix(obj['_empty_']);
2308                    delete obj['_empty_'];
2309                } else {
2310                    obj[i] = this.emptyFix(obj[i]);
2311                }
2312            }
2313        }
2314        return obj
2315    }
2316    /** Function delData
2317     *    Deletes data from JSONStore
2318     *
2319     *  Parameters:
2320     *    (Array) vars  = Variables to delete from JSON store
2321     *
2322     *  Returns:
2323     *    Status of delete attempt.
2324     */
2325    this.delData = function(vars) {
2326        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2327            Strophe.debug("Retrieving JSONStore data");
2328            var xhr = this._newXHR();
2329            var deldata = "del=" + vars.join(",");
2330            try {
2331                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2332            } catch (e) {
2333                Strophe.error("JSONStore open failed.");
2334                return false;
2335            }
2336            xhr.setRequestHeader('Content-type',
2337            'application/x-www-form-urlencoded');
2338            xhr.setRequestHeader('Content-length', deldata.length);
2339            xhr.send(deldata);
2340            if (xhr.readyState == 4 && xhr.status == 200) {
2341                try {
2342                    var dataObj = JSON.parse(xhr.responseText);
2343                    return dataObj;
2344                } catch(e) {
2345                    Strophe.error("Could not parse JSONStore response");
2346                    return false;
2347                }
2348            } else {
2349                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2350                return false;
2351            }
2352        }
2353    }
2354    /** Function setData
2355     *    Stores data in JSONStore, overwriting values if they exist
2356     *
2357     *  Parameters:
2358     *    (Object) vars : Object containing named vars to store ({name: value,
2359     *    othername: othervalue})
2360     *
2361     *  Returns:
2362     *    Status of storage attempt
2363     */
2364    this.setData = function(vars)
2365    {
2366        if ( typeof(TROPHYIM_JSON_STORE) != undefined )
2367        {
2368            var senddata = "set=" + JSON.stringify(vars);
2369            var xhr = this._newXHR();
2370            try
2371            {
2372                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2373            }
2374            catch (e)
2375            {
2376                Strophe.error("JSONStore open failed.");
2377                return false;
2378            }
2379            xhr.setRequestHeader('Content-type',
2380            'application/x-www-form-urlencoded');
2381            xhr.setRequestHeader('Content-length', senddata.length);
2382            xhr.send(senddata);
2383            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
2384            "OK") {
2385                return true;
2386            } else {
2387                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2388                return false;
2389            }
2390        }
2391    }
2392   
2393    var testData = true;
2394   
2395    if (this.setData({testData:testData})) {
2396        var testResult = this.getData(['testData']);
2397        if (testResult && testResult['testData'] == true) {
2398            this.store_working = true;
2399        }
2400    }
2401}
2402/** Constants: Node types
2403 *
2404 * Implementations of constants that IE doesn't have, but we need.
2405 */
2406if (document.ELEMENT_NODE == null) {
2407    document.ELEMENT_NODE = 1;
2408    document.ATTRIBUTE_NODE = 2;
2409    document.TEXT_NODE = 3;
2410    document.CDATA_SECTION_NODE = 4;
2411    document.ENTITY_REFERENCE_NODE = 5;
2412    document.ENTITY_NODE = 6;
2413    document.PROCESSING_INSTRUCTION_NODE = 7;
2414    document.COMMENT_NODE = 8;
2415    document.DOCUMENT_NODE = 9;
2416    document.DOCUMENT_TYPE_NODE = 10;
2417    document.DOCUMENT_FRAGMENT_NODE = 11;
2418    document.NOTATION_NODE = 12;
2419}
2420
2421/** Function: importNode
2422 *
2423 *  document.importNode implementation for IE, which doesn't have importNode
2424 *
2425 *  Parameters:
2426 *    (Object) node - dom object
2427 *    (Boolean) allChildren - import node's children too
2428 */
2429if (!document.importNode) {
2430    document.importNode = function(node, allChildren) {
2431        switch (node.nodeType) {
2432            case document.ELEMENT_NODE:
2433                var newNode = document.createElement(node.nodeName);
2434                if (node.attributes && node.attributes.length > 0) {
2435                    for(var i = 0; i < node.attributes.length; i++) {
2436                        newNode.setAttribute(node.attributes[i].nodeName,
2437                        node.getAttribute(node.attributes[i].nodeName));
2438                    }
2439                }
2440                if (allChildren && node.childNodes &&
2441                node.childNodes.length > 0) {
2442                    for (var i = 0; i < node.childNodes.length; i++) {
2443                        newNode.appendChild(document.importNode(
2444                        node.childNodes[i], allChildren));
2445                    }
2446                }
2447                return newNode;
2448                break;
2449            case document.TEXT_NODE:
2450            case document.CDATA_SECTION_NODE:
2451            case document.COMMENT_NODE:
2452                return document.createTextNode(node.nodeValue);
2453                break;
2454        }
2455    };
2456}
2457
2458/**
2459 *
2460 * Bootstrap self into window.onload and window.onunload
2461 */
2462
2463var oldonunload = window.onunload;
2464
2465window.onunload = function()
2466{
2467        if( oldonunload )
2468        {
2469        oldonunload();
2470    }
2471       
2472        TrophyIM.setPresence('unavailable');
2473}
Note: See TracBrowser for help on using the repository browser.