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

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