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

Revision 3086, 64.0 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 Presence 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        TrophyIM.rosterObj.setPresence( msg.getAttribute('from'), priority, show, status );
648               
649        return true;
650    },
651
652    /** Function : onPresenceChatRoom
653     *
654     *
655     */
656   
657    onPresenceChatRoom : function(msg)
658    {
659        var xquery = msg.getElementsByTagName("x");
660       
661        if ( xquery.length > 0 )
662        {
663                for ( var i = 0; i < xquery.length; i++ )
664            {
665                var xmlns = xquery[i].getAttribute("xmlns");
666               
667                if( xmlns.indexOf("http://jabber.org/protocol/muc#user") == 0 )
668                {
669                        var nameChatRoom = xquery[i].parentNode.getAttribute('from')
670                                nameChatRoom = Strophe.getBareJidFromJid(nameChatRoom);
671
672                        var nickName = xquery[i].firstChild.getAttribute('jid');
673                                nickName = Strophe.getBareJidFromJid( nickName );
674                                nickName = nickName.substring(0, nickName.indexOf('@'));
675                       
676                        var type = xquery[i].parentNode.getAttribute('type') ? xquery[i].parentNode.getAttribute('type') : 'available' ;
677                       
678                        var show = ( xquery[i].parentNode.firstChild.firstChild != null ) ? xquery[i].parentNode.firstChild.firstChild.nodeValue : type ;
679                       
680                        if ( Strophe.getBareJidFromJid( xquery[i].firstChild.getAttribute('jid') ) == Strophe.getBareJidFromJid( TrophyIM.connection.jid ) )
681                                show = loadscript.getStatusUserIM();
682                       
683                        var _UserChatRoom = document.createElement("div");
684                                _UserChatRoom.id = nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid');
685                                _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");
686                                _UserChatRoom.appendChild( document.createTextNode(nickName) );
687               
688                        var nodeUser = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid'));           
689                               
690                        if( nodeUser == null )
691                        {
692                                nameChatRoom = document.getElementById(nameChatRoom + '__roomChat__participants');
693                                nameChatRoom.appendChild( _UserChatRoom );
694                        }
695                        else
696                        {
697                                if( type == 'unavailable' )
698                                {
699                                        nodeUser.parentNode.removeChild( nodeUser );
700                                }
701                                else if( show )
702                                {
703                                        var _UserChatRoom = document.getElementById( nameChatRoom + "_UserChatRoom__" + xquery[i].firstChild.getAttribute('jid') )
704                                       
705                                        _UserChatRoom.setAttribute("style","padding-left:18px ; margin:3px 0px 0px 2px; background: url('"+path_jabberit+"templates/default/images/" + show + ".gif')no-repeat center left");   
706                                }
707                        }
708                }
709            }
710        }
711    },   
712   
713    /** Function: onMessage
714     *
715     *  Message handler
716     */
717   
718    onMessage : function(msg)
719    {
720        var checkTime = function(i)
721        {
722                if ( i < 10 ) i= "0" + i;
723               
724                return i;
725        };
726       
727                var messageDate = function( _date )
728                {
729                        var _dt = _date.substr( 0, _date.indexOf( 'T' ) ).split( '-' );
730                        var _hr = _date.substr( _date.indexOf( 'T' ) + 1, _date.length - _date.indexOf( 'T' ) - 2 ).split( ':' );
731                       
732                        ( _date = new Date ).setTime( Date.UTC( _dt[0], _dt[1] - 1, _dt[2], _hr[0], _hr[1], _hr[2] ) );
733
734                        return ( _date.toLocaleDateString( ).replace( /-/g, '/' ) + ' ' + _date.toLocaleTimeString( ) );
735                };
736
737        var data        = new Date();
738        var dtNow       = checkTime(data.getHours()) + ":" + checkTime(data.getMinutes()) + ":" + checkTime(data.getSeconds());
739       
740        var from        = msg.getAttribute('from');
741        var type        = msg.getAttribute('type');
742        var elems       = msg.getElementsByTagName('body');
743        var delay       = ( msg.getElementsByTagName('delay') ) ? msg.getElementsByTagName('delay') : null;
744        var stamp       = ( delay[0] != null ) ? "<font style='color:red;'>" + messageDate(delay[0].getAttribute('stamp')) + "</font>" :  dtNow;
745
746                var barejid             = Strophe.getBareJidFromJid(from);
747                var jidChatRoom = Strophe.getResourceFromJid(from);
748                var jid_lower   = barejid.toLowerCase();
749                var contact             = "";
750                var state               = "";
751
752                var chatBox     = document.getElementById(jid_lower + "__chatState");
753                var chatStateOnOff = null;
754                var active      = msg.getElementsByTagName('active');
755               
756                contact = barejid.toLowerCase();
757                contact = contact.substring(0, contact.indexOf('@'));
758           
759                if( TrophyIM.rosterObj.roster[barejid] )
760                {
761                        if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
762                        {
763                                contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
764                        }
765                }
766
767                // Message with body are "content message", this means state active
768                if ( elems.length > 0 )
769                {
770                        state = "";
771                       
772                        // Set notify chat state capability on when sender notify it themself
773                        chatStateOnOff = document.getElementById(jid_lower + "__chatStateOnOff");
774                       
775                        if (active.length > 0 & chatStateOnOff != null )
776                        {
777                                chatStateOnOff.value = 'on';
778                        }
779
780                        // Get Message
781                        var _message = document.createElement("div");
782                        _message.innerHTML = Strophe.getText(elems[0]);
783                       
784                        var scripts = _message.getElementsByTagName('script');
785                       
786                        for (var i = 0; i < scripts.length; i++)
787                                _message.removeChild(scripts[i--]);
788                       
789                        _message.innerHTML = _message.innerHTML.replace(/^\s+|\s+$|^\n|\n$/g, "");
790                       
791                        // Get Smiles
792                        _message.innerHTML = loadscript.getSmiles( _message.innerHTML );
793
794                        if (type == 'chat' || type == 'normal')
795                        {
796                                if ( _message.hasChildNodes() )
797                                {
798                                        var message =
799                                        {
800                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + contact + "</font>",
801                                msg             : "</br>" + _message.innerHTML
802                        };
803                                       
804                                        TrophyIM.addMessage( TrophyIM.makeChat( from ), jid_lower, message );
805                                }
806                        }
807                        else if( type == 'groupchat')
808                        {
809                                if ( _message.hasChildNodes() )
810                                {
811                                        var message =
812                                        {
813                                contact : "[" + stamp + "] <font style='font-weight:bold; color:black;'>" + jidChatRoom + "</font>",
814                                msg             : "</br>" + _message.innerHTML
815                        };
816
817                                        TrophyIM.addMessage( TrophyIM.makeChatRoom( barejid ), jid_lower, message );
818                                }
819                        }
820                }
821                // Message without body are "content message", this mean state is not active
822                else
823                {
824                        if( chatBox != null )
825                                state = TrophyIM.getChatState(msg);                     
826                }
827               
828                // Clean chat status message some time later           
829                var clearChatState = function()
830                {
831                        chatBox.innerHTML='';
832                }
833               
834                if (chatBox != null)
835                {
836                        var clearChatStateTimer;
837                       
838                        chatBox.innerHTML = "<font style='font-weight:bold; color:grey; float:right;'>" + state + "</font>";
839                       
840                        var _composing =  msg.getElementsByTagName('composing');
841                       
842                        if ( _composing.length == 0 )
843                               
844                                clearChatStateTimer = setTimeout(clearChatState, 2000);
845                        else
846                                clearTimeout(clearChatStateTimer);                     
847                }
848
849                return true;
850        },
851
852        /** Function: getChatState
853         *
854         *  Parameters:
855         *    (string) msg - the message to get chat state
856         *    (string) jid - the jid of chat box to update the chat state to.
857         */
858        getChatState : function(msg)
859        {
860                var     state =  msg.getElementsByTagName('inactive');
861               
862                if ( state.length > 0 )
863                {
864                return i18n.INACTIVE;
865                }
866                else
867                {
868                state = msg.getElementsByTagName('gone');
869            if ( state.length > 0 )
870            {
871                return i18n.GONE;
872                        }
873            else
874            {
875                state = msg.getElementsByTagName('composing');
876                if ( state.length > 0 )
877                {
878                        return i18n.COMPOSING;
879                                }
880                else
881                {
882                        state =  msg.getElementsByTagName('paused');
883                        if ( state.length > 0 )
884                        {
885                                return i18n.PAUSED;
886                                        }
887                                }
888                        }
889                }
890               
891                return '';
892        },
893
894        /** Function: makeChat
895     *
896     *  Make sure chat window to given fulljid exists, switching chat context to
897     *  given resource.
898     */
899     
900    makeChat : function(fulljid)
901    {
902        var barejid             = Strophe.getBareJidFromJid(fulljid);
903        var titleWindow = "";
904               
905        var paramsChatBox =
906        {
907                        'enabledPopUp'  : ( ( loadscript.getIsIE() ) ? "none" : "block" ),
908                        'idChatBox'     : barejid + "__chatBox",
909                        'jidTo'                 : barejid,
910                                'path_jabberit' : path_jabberit
911        };
912
913        titleWindow = barejid.toLowerCase();
914                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
915
916        if( TrophyIM.rosterObj.roster[barejid] )
917        {
918            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
919            {
920                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
921            }
922        }
923
924        // Position Top
925        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
926        if( TrophyIM.posWindow.top > 200 )
927                TrophyIM.posWindow.top  = 100;
928       
929        // Position Left
930        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
931        if( TrophyIM.posWindow.left > 455 )
932                TrophyIM.posWindow.left = 400;
933       
934        var _content = document.createElement( 'div' );
935        _content.innerHTML = loadscript.parse( "chat_box", "chatBox.xsl", paramsChatBox);
936        _content = _content.firstChild;
937       
938        var _messages           = _content.firstChild.firstChild;
939        var _textarea           = _content.getElementsByTagName( 'textarea' ).item( 0 );
940        var _send                       = _content.getElementsByTagName( 'input' ).item( 0 );
941                var _chatStateOnOff     = _content.getElementsByTagName( 'input' ).item( 1 );
942
943        function _send_message( )
944        {
945                if ( ! TrophyIM.sendMessage( barejid, _textarea.value ) )
946                        return false;
947
948                // Add Message in chatBox;
949                TrophyIM.addMessage( _messages, barejid, {
950                        contact : "<font style='font-weight:bold; color:red;'>" + i18n.ME + "</font>",
951                        msg : "<br/>" + _textarea.value
952                } );
953
954                _textarea.value = '';
955                _textarea.focus( );
956        }
957               
958                var composingTimer_ = 0;
959                var isComposing_ = 0;
960                var timeCounter;
961
962                function setComposing()
963                {
964                        var checkComposing = function()
965                        {
966                if (!isComposing_) {
967                        // User stopped composing
968                        composingTimer_ = 0;
969                        clearInterval(timeCounter);
970                        TrophyIM.sendContentMessage(barejid, 'paused');
971                } else {
972                        TrophyIM.sendContentMessage(barejid, 'composing');
973                }
974                isComposing_ = 0; // Reset composing
975                }
976
977                if (!composingTimer_) {
978                /* User (re)starts composing */
979                composingTimer_ = 1;
980                timeCounter = setInterval(checkComposing,4000);
981                }
982                isComposing_ = 1;
983        }
984
985        loadscript.configEvents( _send, 'onclick', _send_message );
986                loadscript.configEvents( _textarea, 'onkeyup', function( e )
987                {
988                        if ( e.keyCode == 13 ){
989                                _send_message( );
990                                // User stopped composing
991                composingTimer_ = 0;
992                clearInterval(timeCounter);
993                        }else{
994                                if (_chatStateOnOff.value == 'on')
995                                        setComposing();
996                        }
997                } );       
998
999        var winChatBox =
1000        {
1001                         id_window              : "window_chat_area_" + barejid,
1002                         barejid                : barejid,
1003                         width                  : 387,
1004                         height                 : 375,
1005                         top                    : TrophyIM.posWindow.top,
1006                         left                   : TrophyIM.posWindow.left,
1007                         draggable              : true,
1008                         visible                : "display",
1009                         resizable              : true,
1010                         zindex                 : loadscript.getZIndex(),
1011                         title                  : titleWindow,
1012                         closeAction    : "hidden",
1013                         content                : _content     
1014        }
1015       
1016                _win = _winBuild(winChatBox);
1017
1018        // Notification New Message
1019        loadscript.notification(barejid);
1020       
1021        // Photo User;
1022                loadscript.getPhotoUser(barejid);
1023               
1024                _textarea.focus( );
1025               
1026                return ( _messages = _win.content( ).firstChild );
1027    },
1028
1029        /** Function: makeChatRoom
1030    *
1031    *
1032    *
1033    */
1034   
1035    makeChatRoom : function()
1036    {
1037        var jidChatRoom = arguments[0];
1038        var titleWindow = "ChatRoom - " + arguments[1];
1039       
1040       
1041        var paramsChatRoom =
1042        {
1043                        'idChatRoom'    : jidChatRoom + "__roomChat",
1044                        'jidTo'                 : jidChatRoom,
1045                                'path_jabberit' : path_jabberit
1046        };
1047
1048        // Position Top
1049        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
1050        if( TrophyIM.posWindow.top > 200 )
1051                TrophyIM.posWindow.top  = 100;
1052       
1053        // Position Left
1054        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
1055        if( TrophyIM.posWindow.left > 455 )
1056                TrophyIM.posWindow.left = 400;
1057
1058        var _content = document.createElement( 'div' );
1059        _content.innerHTML = loadscript.parse( "chat_room", "chatRoom.xsl", paramsChatRoom );
1060        _content = _content.firstChild;
1061       
1062        var _messages           = _content.firstChild.firstChild;
1063       
1064        var winChatRoom =
1065        {
1066                         id_window              : "window_chat_room_" + arguments[0],
1067                         barejid                : jidChatRoom,
1068                         width                  : 500,
1069                         height                 : 450,
1070                         top                    : TrophyIM.posWindow.top,
1071                         left                   : TrophyIM.posWindow.left,
1072                         draggable              : true,
1073                         visible                : "display",
1074                         resizable              : true,
1075                         zindex                 : loadscript.getZIndex(),
1076                         title                  : titleWindow,
1077                         closeAction    : "hidden",
1078                         content                : _content     
1079        }
1080       
1081        _win = _winBuild(winChatRoom);
1082       
1083        return ( _messages = _win.content( ).firstChild );
1084       
1085    },
1086   
1087        /** Function addContacts
1088         *
1089         *  Parameters:
1090         *              (string) jidFrom         
1091         *      (string) jidTo
1092         *              (string) name
1093         *              (string) group   
1094         */
1095       
1096        addContact : function( jidTo, name, group )
1097        {
1098                // Add Contact
1099        var _id = TrophyIM.connection.getUniqueId('add');
1100                var newContact = $iq({type: 'set', id: _id });
1101                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1102                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
1103                        newContact = newContact.c('group').t(group).tree();
1104
1105                TrophyIM.connection.send(newContact);
1106        },
1107
1108    /** Function: add
1109     *
1110     *  Parameters:
1111     *    (string) msg - the message to add
1112     *    (string) jid - the jid of chat box to add the message to.
1113     */
1114       
1115    addMessage : function( chatBox, jid, msg )
1116    {
1117        // Get Smiles
1118        msg.msg = loadscript.getSmiles( msg.msg );
1119 
1120        var messageDiv  = document.createElement("div");
1121                messageDiv.style.margin = "3px 0px 1em 3px";
1122        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
1123               
1124        chatBox.appendChild(messageDiv);
1125        chatBox.scrollTop = chatBox.scrollHeight;
1126    },
1127       
1128    /** Function : renameContact
1129     *
1130     *
1131     */
1132   
1133    renameContact : function( jid )
1134    {
1135        // Name
1136        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
1137
1138                if(( name = prompt(i18n.ASK_NEW_NAME_QUESTION + name + "!", name )))
1139                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1140                                name = "";
1141
1142                if( name == null || name == "")
1143                        name = "";
1144               
1145        var jidTo = jid
1146        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
1147        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1148       
1149        TrophyIM.addContact( jidTo, name, group );
1150       
1151        document.getElementById('itenContact_' + jid ).innerHTML = name;
1152    },
1153   
1154    /** Function : renameGroup
1155     *
1156     *
1157     */
1158
1159    renameGroup : function( jid )
1160    {
1161        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
1162        var presence    = TrophyIM.rosterObj.roster[jid].presence;
1163       
1164                // Group
1165                if(( group = prompt( i18n.ASK_NEW_GROUP_QUESTION, group )))
1166                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
1167                                group = "";
1168
1169                if( group == null || group == "")
1170                        group = "";
1171
1172        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
1173        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
1174                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
1175
1176                TrophyIM.rosterObj.removeContact( jid );
1177               
1178                TrophyIM.addContact( jidTo, name, group );
1179       
1180                document.getElementById("JabberIMRoster").innerHTML = "";
1181               
1182        TrophyIM.renderRoster();
1183       
1184        setTimeout(function()
1185        {
1186                for( var i in presence )
1187                {
1188                        if ( presence[ i ].constructor == Function )
1189                                continue;
1190                               
1191                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
1192                }
1193        },500);
1194    },
1195
1196    // TESTE SALAS
1197   
1198    /** Function : joinRoom
1199     *
1200     *
1201     */
1202   
1203    joinRoom : function( roomName )
1204    {
1205        var msg = $pres({from: TrophyIM.connection.jid, to: roomName}).c("x",{xmlns: Strophe.NS.MUC});
1206       
1207                TrophyIM.connection.send(msg);
1208    },
1209   
1210    /** Function : getlistRooms
1211     *
1212     *
1213     */
1214   
1215    getListRooms : function()
1216    {
1217        var _error_return = function(element)
1218        {
1219                alert( " ERROR : " + element );
1220        };
1221       
1222                var iq = $iq({to: "conference.im.pr.gov.br", type: "get"}).c("query",{xmlns: Strophe.NS.DISCO_ITEMS});                 
1223               
1224        TrophyIM.connection.sendIQ( iq, loadscript.listRooms, _error_return, 500 );             
1225    },
1226   
1227    /** Function: removeContact
1228     *
1229     *  Parameters:
1230     *          (string) jidTo
1231     */
1232   
1233    removeContact : function( jidTo )
1234    {
1235        var divItenContact       = null;
1236
1237        if( ( divItenContact = document.getElementById('itenContact_' + jidTo )))
1238        {       
1239                // Remove Contact
1240                var _id = TrophyIM.connection.getUniqueId();   
1241                var delContact  = $iq({type: 'set', id: _id})
1242                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
1243                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
1244
1245                TrophyIM.connection.send( delContact );
1246               
1247                        loadscript.removeElement( document.getElementById('itenContactNotification_' + jidTo ) );
1248               
1249                var spanShow = document.getElementById('span_show_itenContact_' + jidTo )
1250                        spanShow.parentNode.removeChild(spanShow);
1251               
1252                loadscript.removeGroup( divItenContact.parentNode );
1253               
1254                divItenContact.parentNode.removeChild(divItenContact);
1255        }
1256    },
1257   
1258    /** Function: renderRoster
1259     *
1260     *  Renders roster, looking only for jids flagged by setPresence as having
1261     *  changed.
1262     */
1263   
1264        renderRoster : function()
1265        {
1266                var roster_div = document.getElementById('JabberIMRoster');
1267               
1268                if( roster_div )
1269                {
1270                        var users = new Array();
1271                       
1272                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1273                       
1274                        if( loading_gif.style.display == "block" )
1275                                loading_gif.style.display = "none";
1276                               
1277                        for( var user in TrophyIM.rosterObj.roster )
1278                        {
1279                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
1280                                        continue;
1281
1282                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
1283                        }
1284
1285                        users.sort();
1286                       
1287                        var groups              = new Array();
1288                        var flagGeral   = false;
1289                       
1290                        for (var group in TrophyIM.rosterObj.groups)
1291                        {
1292                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
1293                                        continue;
1294                               
1295                                if( group )
1296                                        groups[groups.length] = group;
1297                               
1298                                if( group == "Geral" )
1299                                        flagGeral = true;
1300            }
1301           
1302                        if( !flagGeral && users.length > 0 )
1303                                groups[groups.length] = "Geral";
1304                               
1305                        groups.sort();
1306                       
1307                        for ( var i = 0; i < groups.length; i++ )
1308                        {
1309                                TrophyIM.renderGroups( groups[i] , roster_div );       
1310                        }
1311                       
1312                        TrophyIM.renderItensGroup( users, roster_div );
1313                }
1314                       
1315                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
1316        },
1317       
1318    /** Function: renderGroups
1319     *
1320     *
1321     */
1322       
1323        renderGroups: function( nameGroup, element )
1324        {
1325                var _addGroup = function()
1326                {
1327                        var _nameGroup  = nameGroup;
1328                        var _element    = element;
1329
1330                        var paramsGroup =
1331                        {
1332                                'nameGroup'     : _nameGroup,
1333                                'path_jabberit' : path_jabberit
1334                        }
1335                       
1336                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
1337                }
1338
1339                if( !element.hasChildNodes() )
1340                {
1341                        _addGroup();
1342                }
1343                else
1344                {
1345                        var _NodeChild  = element.firstChild;
1346                        var flagAdd             = false;
1347                       
1348                        while( _NodeChild )
1349                        {
1350                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1351                                {
1352                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
1353                                        {
1354                                                flagAdd = true;
1355                                        }
1356                                }
1357                               
1358                                _NodeChild = _NodeChild.nextSibling;
1359                        }
1360
1361                        if( !flagAdd )
1362                        {
1363                                _addGroup();
1364                        }
1365                }
1366        },
1367
1368    /** Function: renderItensGroup
1369     *
1370     *
1371     */
1372
1373        renderItensGroup : function( users, element )
1374        {
1375                var addItem = function()
1376                {
1377                        if( arguments.length > 0 )
1378                        {
1379                                // Get Arguments
1380                                var objContact  = arguments[0];
1381                                var group               = arguments[1];
1382                                var element             = arguments[2];
1383                                var showOffline = loadscript.getShowContactsOffline();
1384                               
1385                                // Presence e Status
1386                                var presence            = "unavailable";
1387                                var status                      = "";
1388                                var statusColor         = "black";
1389                                var statusDisplay       = "none";
1390                               
1391                                var _resource   = "";
1392                               
1393                                // Set Presence
1394                                var _presence = function(objContact)
1395                                {
1396                                        if (objContact.presence)
1397                                        {
1398                                                for (var resource in objContact.presence)
1399                                                {
1400                                                        if ( objContact.presence[resource].constructor == Function )
1401                                                                continue;
1402
1403                                                        if( objContact.presence[resource].show != 'invisible' )
1404                                                                presence = objContact.presence[resource].show;
1405
1406                                                        if( objContact.contact.subscription != "both")
1407                                                                presence = 'subscription';
1408                                                       
1409                                                        if( objContact.presence[resource].status )
1410                                                        {
1411                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1412                                                                statusDisplay   = "block";
1413                                                        }
1414                                                }
1415                                        }
1416                                };
1417                               
1418                                // Set Subscription
1419                                var _subscription = function( objContact )
1420                                {
1421                                        if( objContact.contact.subscription != "both" )
1422                                        {
1423                                                switch( objContact.contact.subscription )
1424                                                {
1425                                                        case "none" :
1426                                                               
1427                                                                status          = " (( " + i18n.ASK_FOR_AUTH  + " )) ";
1428                                                                statusColor     = "red";
1429                                                                break;
1430       
1431                                                        case "to" :
1432                                                               
1433                                                                status          = " (( " + i18n.CONTACT_ASK_FOR_AUTH  + " )) ";
1434                                                                statusColor     = "orange";
1435                                                                break;
1436       
1437                                                        case "from" :
1438                                                               
1439                                                                status          = " (( " + i18n.AUTHORIZED + " )) ";
1440                                                                statusColor = "green";
1441                                                                break;
1442                                                               
1443                                                        case "subscribe" :
1444                                                               
1445                                                                status          = " (( " + i18n.AUTH_SENT  + " )) ";
1446                                                                statusColor     = "red";       
1447                                                                break;
1448
1449                                                        case "not-in-roster" :
1450                                                               
1451                                                                status          = " (( " + i18n.ASK_FOR_AUTH_QUESTION  + " )) ";
1452                                                                statusColor     = "orange";     
1453                                                                break;
1454                                                               
1455                                                        default :
1456                                                               
1457                                                                break;
1458                                                }
1459
1460                                                statusDisplay = "block";
1461                                        }
1462                                };
1463
1464                                if( objContact.contact.subscription != "remove")
1465                                {
1466                                        var itensJid    = document.getElementById( "itenContact_" + objContact.contact.jid );
1467                                       
1468                                        if( itensJid == null )
1469                                        {
1470                                                // Name
1471                                                var nameContact = "";                                   
1472                                               
1473                                                if ( objContact.contact.name )
1474                                                        nameContact = objContact.contact.name;
1475                                                else
1476                                                {
1477                                                        nameContact = objContact.contact.jid;
1478                                                        nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1479                                                }
1480                                               
1481                                                // Get Presence
1482                                                _presence(objContact);
1483                                               
1484                                                var paramsContact =
1485                                                {
1486                                                        divDisplay              : "block",
1487                                                        id                              : 'itenContact_' + objContact.contact.jid ,
1488                                                        jid                             : objContact.contact.jid,
1489                                                        nameContact     : nameContact,
1490                                                        path_jabberit   : path_jabberit,
1491                                                        presence                : presence,
1492                                                        spanDisplay             : statusDisplay,
1493                                                        status                  : status,
1494                                                        statusColor             : "black",
1495                                                        subscription    : objContact.contact.subscription,
1496                                                        resource                : _resource
1497                                                }
1498                                               
1499                                                // Get Authorization
1500                                                _subscription( objContact );
1501                                               
1502                                                if( group != "")
1503                                                {
1504                                                        var _NodeChild          = element.firstChild;
1505                                                       
1506                                                        while( _NodeChild )
1507                                                        {
1508                                                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1509                                                                {
1510                                                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1511                                                                        {
1512                                                                                _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1513                                                                        }
1514                                                                }
1515       
1516                                                                _NodeChild = _NodeChild.nextSibling;
1517                                                        }
1518                                                }       
1519                                        }
1520                                        else
1521                                        {
1522                                                // Get Presence
1523                                                _presence(objContact);
1524       
1525                                                var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1526                                                        is_open = is_open.indexOf("arrow_down.gif");
1527       
1528                                                // Get Authorization
1529                                                _subscription( objContact );
1530                                               
1531                                                // Set subscription
1532                                                itensJid.setAttribute('subscription', objContact.contact.subscription );
1533                                               
1534                                                with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ) )
1535                                                {
1536                                                        if( presence == "unavailable" && !showOffline )
1537                                                        {
1538                                                                style.display = "none";
1539                                                        }
1540                                                        else
1541                                                        {
1542                                                                if( is_open > 0 )
1543                                                                {
1544                                                                        style.display   = statusDisplay;
1545                                                                        style.color             = statusColor;
1546                                                                        innerHTML               = status;
1547                                                                }
1548                                                        }
1549                                                }
1550                                               
1551                                                if( presence == "unavailable" && !showOffline )
1552                                                {
1553                                                        itensJid.style.display = "none";
1554                                                }
1555                                                else
1556                                                {
1557                                                        if( is_open > 0 )
1558                                                        {
1559                                                                itensJid.style.display = "block";
1560                                                        }
1561                                                }
1562                                               
1563                                                itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1564                                        }
1565       
1566                                        // Contact OffLine
1567                                        if( !objContact.presence && !showOffline )
1568                                        {
1569                                                if( objContact.contact.subscription != "remove" )
1570                                                {
1571                                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid ))
1572                                                        {
1573                                                                style.display   = "none";
1574                                                        }
1575               
1576                                                        with ( document.getElementById('itenContact_' + objContact.contact.jid ) )
1577                                                        {
1578                                                                style.display   = "none";
1579                                                        }
1580                                                }
1581                                        }
1582                                }
1583                        }
1584                };
1585               
1586                var flag = false;
1587               
1588                for( var i = 0 ; i < users.length; i++ )
1589                {
1590                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode( loadscript.getUserCurrent().jid) )
1591                        {
1592                                var _subscription = TrophyIM.rosterObj.roster[users[i]].contact.subscription;
1593                               
1594                                if( _subscription === "to" )
1595                                {
1596                                        flag = true;
1597                                }
1598                               
1599                                if(  _subscription === "not-in-roster")
1600                                {
1601                                        flag = true;
1602                                }
1603                               
1604                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1605                                {
1606                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1607                                       
1608                                        if( groups.length > 0 )
1609                                        {
1610                                                for( var j = 0; j < groups.length; j++ )
1611                                                {
1612                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element );
1613                                                }
1614                                        }
1615                                        else
1616                                        {
1617                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1618                                        }
1619                                }
1620                                else
1621                                {
1622                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element );
1623                                }
1624                        }
1625                }
1626               
1627                if( flag )
1628                {
1629                        if ( TrophyIM.controll.notificationNewUsers == 0 )
1630                        {
1631                                loadscript.enabledNotificationNewUsers();
1632                                TrophyIM.controll.notificationNewUsers++;
1633                        }
1634                }
1635                else
1636                {
1637                        loadscript.disabledNotificationNewUsers();
1638                        TrophyIM.controll.notificationNewUsers = 0;
1639                }
1640        },
1641
1642    /** Function: rosterClick
1643     *
1644     *  Handles actions when a roster item is clicked
1645     */
1646   
1647        rosterClick : function(fulljid)
1648        {
1649        TrophyIM.makeChat(fulljid);
1650    },
1651
1652        /** Function SetAutorization
1653         *
1654         */
1655
1656        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1657        {
1658        var _id = TrophyIM.connection.getUniqueId();
1659       
1660        TrophyIM.connection.send($pres( ).attrs({ from: jidFrom, to: jidTo, type: _typeSubscription, id: _id }).tree());
1661        },
1662   
1663        /** Function: setPresence
1664     *
1665     */
1666
1667        setPresence : function( _type )
1668        {
1669                if( _type != 'status')
1670                {
1671                        if( _type == "unavailable" &&  TrophyIM.statusConn.connected )
1672                        {
1673                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1674                               
1675                                if( TrophyIM._timeOut.renderRoster != null )
1676                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1677                               
1678                                if( TrophyIM.statusConn.connected )
1679                                        TrophyIM.connection.send($pres({type : _type}).tree());
1680                               
1681                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1682                        {
1683                                if( TrophyIM.connection._requests[i] )
1684                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1685                        }
1686                               
1687                                TrophyIM.logout();
1688                               
1689                        loadscript.clrAllContacts();
1690                       
1691                        delete TrophyIM.rosterObj.roster;
1692                        delete TrophyIM.rosterObj.groups;
1693                       
1694                        setTimeout(function()
1695                        {
1696                                        if( loading_gif.style.display == "block" )
1697                                                loading_gif.style.display = "none";
1698                        }, 1000);
1699                        }
1700                        else
1701                        {
1702                                if( !TrophyIM.autoConnection.connect )
1703                                {
1704                                        TrophyIM.autoConnection.connect = true;
1705                                        TrophyIM.load();
1706                                }
1707                                else
1708                                {
1709                                        if( TrophyIM.statusConn.connected )
1710                                        {
1711                                                if( loadscript.getStatusMessage() != "" )
1712                                                {
1713                                                        var _presence = $pres( );
1714                                                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1715                                                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1716                                                       
1717                                                        TrophyIM.connection.send( _presence.tree() );
1718                                                }
1719                                                else
1720                                                {
1721                                                        TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1722                                                }
1723                                        }
1724                                }
1725                        }
1726                }
1727                else
1728                {
1729                        var _show       = "available";
1730                        var _status     = "";
1731                       
1732                        if( arguments.length < 2 )
1733                        {
1734                                if( loadscript.getStatusMessage() != "" )
1735                                        _status = prompt(i18n.TYPE_YOUR_MSG, loadscript.getStatusMessage());
1736                                else
1737                                        _status = prompt(i18n.TYPE_YOUR_MSG);
1738                               
1739                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1740                               
1741                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1742                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1743                        }
1744                        else
1745                        {
1746                                _status = arguments[1];
1747                        }
1748
1749                        for( var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1750                        {
1751                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1752                                continue;
1753                       
1754                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1755                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1756                        }
1757
1758                        if ( TrophyIM.statusConn.connected )
1759                        {
1760                                var _presence = $pres( );
1761                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1762                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1763                               
1764                                TrophyIM.connection.send( _presence.tree() );
1765                        }
1766                }
1767        },
1768       
1769        /** Function: sendMessage
1770     *
1771     *  Send message from chat input to user
1772     */
1773     
1774    sendMessage : function()
1775    {
1776                if (arguments.length > 0) {
1777                        var jidTo = arguments[0];
1778                        var message_input = arguments[1];
1779                       
1780                       
1781                        message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g, "");
1782                       
1783                        if (message_input != "") {
1784                       
1785                                // Send Message
1786                                var newMessage = $msg({
1787                                        to: jidTo,
1788                                        from: TrophyIM.connection.jid,
1789                                        type: 'chat'
1790                                });
1791                                newMessage = newMessage.c('body').t(message_input);
1792                                newMessage.up();
1793                                newMessage = newMessage.c('active').attrs({
1794                                        xmlns: 'http://jabber.org/protocol/chatstates'
1795                                });
1796                                // Send Message
1797                                TrophyIM.connection.send(newMessage.tree());
1798                               
1799                                return true;
1800                        }
1801                }
1802               
1803                return false;
1804    },
1805       
1806        /** Function: sendContentMessage
1807     *
1808     *  Send a content message from chat input to user
1809     */
1810        sendContentMessage : function()
1811    {
1812      if( arguments.length > 0 )
1813      {
1814         var jidTo = arguments[0];
1815         var state = arguments[1];
1816
1817         var newMessage = $msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'});
1818         newMessage = newMessage.c(state).attrs({xmlns : 'http://jabber.org/protocol/chatstates'});
1819         // Send content message
1820         TrophyIM.connection.send(newMessage.tree());
1821      }
1822    }
1823};
1824
1825/** Class: TrophyIMRoster
1826 *
1827 *
1828 *  This object stores the roster and presence info for the TrophyIMClient
1829 *
1830 *  roster[jid_lower]['contact']
1831 *  roster[jid_lower]['presence'][resource]
1832 */
1833function TrophyIMRoster()
1834{
1835    /** Constants: internal arrays
1836     *    (Object) roster - the actual roster/presence information
1837     *    (Object) groups - list of current groups in the roster
1838     *    (Array) changes - array of jids with presence changes
1839     */
1840    if (TrophyIM.JSONStore.store_working)
1841        {
1842        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1843        this.roster = (data['roster'] != null) ? data['roster'] : {};
1844        this.groups = (data['groups'] != null) ? data['groups'] : {};
1845    }
1846        else
1847        {
1848        this.roster = {};
1849        this.groups = {};
1850    }
1851    this.changes = new Array();
1852   
1853        if (TrophyIM.constants.stale_roster)
1854        {
1855        for (var jid in this.roster)
1856                {
1857                        this.changes[this.changes.length] = jid;
1858        }
1859    }
1860
1861        /** Function: addChange
1862         *
1863         *  Adds given jid to this.changes, keeping this.changes sorted and
1864         *  preventing duplicates.
1865         *
1866         *  Parameters
1867         *    (String) jid : jid to add to this.changes
1868         */
1869         
1870        this.addChange = function(jid)
1871        {
1872                for (var c = 0; c < this.changes.length; c++)
1873                {
1874                        if (this.changes[c] == jid)
1875                        {
1876                                return;
1877                        }
1878                }
1879               
1880                this.changes[this.changes.length] = jid;
1881               
1882                this.changes.sort();
1883        }
1884       
1885    /** Function: addContact
1886     *
1887     *  Adds given contact to roster
1888     *
1889     *  Parameters:
1890     *    (String) jid - bare jid
1891     *    (String) subscription - subscription attribute for contact
1892     *    (String) name - name attribute for contact
1893     *    (Array)  groups - array of groups contact is member of
1894     */
1895   
1896        this.addContact = function(jid, subscription, name, groups )
1897        {
1898                if( subscription === "remove" )
1899        {
1900                        this.removeContact(jid);
1901        }
1902        else
1903        {
1904                        var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
1905                var jid_lower   = jid.toLowerCase();
1906       
1907                        if ( this.roster[jid_lower] )
1908                        {
1909                    this.roster[jid_lower]['contact'] = contact;
1910                }
1911                        else
1912                        {
1913                    this.roster[jid_lower] = {contact:contact};
1914                }
1915
1916                        groups = groups ? groups : [''];
1917               
1918                        for ( var g = 0; g < groups.length; g++ )
1919                        {
1920                                if ( !this.groups[groups[g]] )
1921                                {
1922                        this.groups[groups[g]] = {};
1923                    }
1924                   
1925                                this.groups[groups[g]][jid_lower] = jid_lower;
1926                }
1927        }
1928    }
1929   
1930    /** Function: getContact
1931     *
1932     *  Returns contact entry for given jid
1933     *
1934     *  Parameter: (String) jid - jid to return
1935     */
1936     
1937    this.getContact = function(jid)
1938        {
1939        if (this.roster[jid.toLowerCase()])
1940                {
1941            return this.roster[jid.toLowerCase()]['contact'];
1942        }
1943    }
1944
1945   /** Function: getPresence
1946        *
1947        *  Returns best presence for given jid as Array(resource, priority, show,
1948        *  status)
1949        *
1950        *  Parameter: (String) fulljid - jid to return best presence for
1951        */
1952         
1953        this.getPresence = function(fulljid)
1954        {
1955                var jid = Strophe.getBareJidFromJid(fulljid);
1956                var current = null;
1957                   
1958                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
1959                {
1960                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
1961                        {
1962                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
1963                                continue;
1964                       
1965                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1966                                if (current == null)
1967                                {
1968                                        current = presence
1969                                }
1970                                else
1971                                {
1972                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1973                                        || presence['show'] == "available") || (current['show'] != "chat" ||
1974                                        current['show'] != "available")))
1975                                        {
1976                                                current = presence
1977                                        }
1978                                }
1979                        }
1980                }
1981                return current;
1982        }
1983
1984        /** Function: groupHasChanges
1985         *
1986         *  Returns true if current group has members in this.changes
1987         *
1988         *  Parameters:
1989         *    (String) group - name of group to check
1990         */
1991         
1992        this.groupHasChanges = function(group)
1993        {
1994                for (var c = 0; c < this.changes.length; c++)
1995                {
1996                        if (this.groups[group][this.changes[c]])
1997                        {
1998                                return true;
1999                        }
2000                }
2001                return false;
2002        }
2003       
2004        /** Function removeContact
2005         *
2006         * Parameters
2007         *       (String) jid           
2008         */
2009         
2010         this.removeContact = function(jid)
2011         {
2012                if( this.roster[ jid ] )
2013                {
2014                        var groups = this.roster[ jid ].contact.groups;
2015                       
2016                        if( groups )
2017                        {
2018                                for ( var i = 0; i < groups.length; i++ )
2019                                {
2020                                        delete this.groups[ groups[ i ] ][ jid ];
2021                                }
2022       
2023                                for ( var i = 0; i < groups.length; i++ )
2024                                {
2025                                        var contacts = 0;
2026                                        for ( var contact in this.groups[ groups[ i ] ] )
2027                                        {
2028                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
2029                                                continue;
2030                                       
2031                                                contacts++;
2032                                        }
2033               
2034                                        if ( ! contacts )
2035                                                delete this.groups[ groups[ i ] ];
2036                                }
2037                        }
2038       
2039                        // Delete Object roster
2040                        if( this.roster[jid] )
2041                                delete this.roster[jid];
2042                }
2043         }
2044         
2045    /** Function: setPresence
2046     *
2047     *  Sets presence
2048     *
2049     *  Parameters:
2050     *    (String) fulljid: full jid with presence
2051     *    (Integer) priority: priority attribute from presence
2052     *    (String) show: show attribute from presence
2053     *    (String) status: status attribute from presence
2054     */
2055   
2056        this.setPresence = function(fulljid, priority, show, status)
2057        {
2058                var barejid             = Strophe.getBareJidFromJid(fulljid);
2059        var resource    = Strophe.getResourceFromJid(fulljid);
2060        var jid_lower   = barejid.toLowerCase();
2061       
2062        if( show != 'unavailable' || show != 'error' )
2063                {
2064            if (!this.roster[jid_lower])
2065                        {
2066                this.addContact( barejid, 'not-in-roster' );
2067            }
2068           
2069            var presence =
2070                        {
2071                resource        : resource,
2072                priority        : priority,
2073                show            : show,
2074                status          : status
2075            }
2076           
2077                        if (!this.roster[jid_lower]['presence'])
2078                        {
2079                this.roster[jid_lower]['presence'] = {};
2080            }
2081           
2082            this.roster[jid_lower]['presence'][resource] = presence;   
2083                }
2084    }
2085
2086        /** Fuction: save
2087         *
2088         *  Saves roster data to JSON store
2089         */
2090       
2091        this.save = function()
2092        {
2093                if (TrophyIM.JSONStore.store_working)
2094                {
2095                        TrophyIM.JSONStore.setData({roster:this.roster,
2096                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
2097                        chat_history:TrophyIM.chatHistory});
2098                }
2099        }
2100
2101}
2102/** Class: TrophyIMJSONStore
2103 *
2104 *
2105 *  This object is the mechanism by which TrophyIM stores and retrieves its
2106 *  variables from the url provided by TROPHYIM_JSON_STORE
2107 *
2108 */
2109function TrophyIMJSONStore() {
2110    this.store_working = false;
2111    /** Function _newXHR
2112     *
2113     *  Set up new cross-browser xmlhttprequest object
2114     *
2115     *  Parameters:
2116     *    (function) handler = what to set onreadystatechange to
2117     */
2118     this._newXHR = function (handler) {
2119        var xhr = null;
2120        if (window.XMLHttpRequest) {
2121            xhr = new XMLHttpRequest();
2122            if (xhr.overrideMimeType) {
2123            xhr.overrideMimeType("text/xml");
2124            }
2125        } else if (window.ActiveXObject) {
2126            xhr = new ActiveXObject("Microsoft.XMLHTTP");
2127        }
2128        return xhr;
2129    }
2130    /** Function getData
2131     *  Gets data from JSONStore
2132     *
2133     *  Parameters:
2134     *    (Array) vars = Variables to get from JSON store
2135     *
2136     *  Returns:
2137     *    Object with variables indexed by names given in parameter 'vars'
2138     */
2139    this.getData = function(vars) {
2140        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2141            Strophe.debug("Retrieving JSONStore data");
2142            var xhr = this._newXHR();
2143            var getdata = "get=" + vars.join(",");
2144            try {
2145                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2146            } catch (e) {
2147                Strophe.error("JSONStore open failed.");
2148                return false;
2149            }
2150            xhr.setRequestHeader('Content-type',
2151            'application/x-www-form-urlencoded');
2152            xhr.setRequestHeader('Content-length', getdata.length);
2153            xhr.send(getdata);
2154            if (xhr.readyState == 4 && xhr.status == 200) {
2155                try {
2156                    var dataObj = JSON.parse(xhr.responseText);
2157                    return this.emptyFix(dataObj);
2158                } catch(e) {
2159                    Strophe.error("Could not parse JSONStore response" +
2160                    xhr.responseText);
2161                    return false;
2162                }
2163            } else {
2164                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2165                return false;
2166            }
2167        }
2168    }
2169    /** Function emptyFix
2170     *    Fix for bugs in external JSON implementations such as
2171     *    http://bugs.php.net/bug.php?id=41504.
2172     *    A.K.A. Don't use PHP, people.
2173     */
2174    this.emptyFix = function(obj) {
2175        if (typeof(obj) == "object") {
2176            for (var i in obj) {
2177                        if ( obj[i].constructor == Function )
2178                                continue;
2179                       
2180                if (i == '_empty_') {
2181                    obj[""] = this.emptyFix(obj['_empty_']);
2182                    delete obj['_empty_'];
2183                } else {
2184                    obj[i] = this.emptyFix(obj[i]);
2185                }
2186            }
2187        }
2188        return obj
2189    }
2190    /** Function delData
2191     *    Deletes data from JSONStore
2192     *
2193     *  Parameters:
2194     *    (Array) vars  = Variables to delete from JSON store
2195     *
2196     *  Returns:
2197     *    Status of delete attempt.
2198     */
2199    this.delData = function(vars) {
2200        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
2201            Strophe.debug("Retrieving JSONStore data");
2202            var xhr = this._newXHR();
2203            var deldata = "del=" + vars.join(",");
2204            try {
2205                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2206            } catch (e) {
2207                Strophe.error("JSONStore open failed.");
2208                return false;
2209            }
2210            xhr.setRequestHeader('Content-type',
2211            'application/x-www-form-urlencoded');
2212            xhr.setRequestHeader('Content-length', deldata.length);
2213            xhr.send(deldata);
2214            if (xhr.readyState == 4 && xhr.status == 200) {
2215                try {
2216                    var dataObj = JSON.parse(xhr.responseText);
2217                    return dataObj;
2218                } catch(e) {
2219                    Strophe.error("Could not parse JSONStore response");
2220                    return false;
2221                }
2222            } else {
2223                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2224                return false;
2225            }
2226        }
2227    }
2228    /** Function setData
2229     *    Stores data in JSONStore, overwriting values if they exist
2230     *
2231     *  Parameters:
2232     *    (Object) vars : Object containing named vars to store ({name: value,
2233     *    othername: othervalue})
2234     *
2235     *  Returns:
2236     *    Status of storage attempt
2237     */
2238    this.setData = function(vars)
2239    {
2240        if ( typeof(TROPHYIM_JSON_STORE) != undefined )
2241        {
2242            var senddata = "set=" + JSON.stringify(vars);
2243            var xhr = this._newXHR();
2244            try
2245            {
2246                xhr.open("POST", TROPHYIM_JSON_STORE, false);
2247            }
2248            catch (e)
2249            {
2250                Strophe.error("JSONStore open failed.");
2251                return false;
2252            }
2253            xhr.setRequestHeader('Content-type',
2254            'application/x-www-form-urlencoded');
2255            xhr.setRequestHeader('Content-length', senddata.length);
2256            xhr.send(senddata);
2257            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
2258            "OK") {
2259                return true;
2260            } else {
2261                Strophe.error("JSONStore open failed. Status: " + xhr.status);
2262                return false;
2263            }
2264        }
2265    }
2266   
2267    var testData = true;
2268   
2269    if (this.setData({testData:testData})) {
2270        var testResult = this.getData(['testData']);
2271        if (testResult && testResult['testData'] == true) {
2272            this.store_working = true;
2273        }
2274    }
2275}
2276/** Constants: Node types
2277 *
2278 * Implementations of constants that IE doesn't have, but we need.
2279 */
2280if (document.ELEMENT_NODE == null) {
2281    document.ELEMENT_NODE = 1;
2282    document.ATTRIBUTE_NODE = 2;
2283    document.TEXT_NODE = 3;
2284    document.CDATA_SECTION_NODE = 4;
2285    document.ENTITY_REFERENCE_NODE = 5;
2286    document.ENTITY_NODE = 6;
2287    document.PROCESSING_INSTRUCTION_NODE = 7;
2288    document.COMMENT_NODE = 8;
2289    document.DOCUMENT_NODE = 9;
2290    document.DOCUMENT_TYPE_NODE = 10;
2291    document.DOCUMENT_FRAGMENT_NODE = 11;
2292    document.NOTATION_NODE = 12;
2293}
2294
2295/** Function: importNode
2296 *
2297 *  document.importNode implementation for IE, which doesn't have importNode
2298 *
2299 *  Parameters:
2300 *    (Object) node - dom object
2301 *    (Boolean) allChildren - import node's children too
2302 */
2303if (!document.importNode) {
2304    document.importNode = function(node, allChildren) {
2305        switch (node.nodeType) {
2306            case document.ELEMENT_NODE:
2307                var newNode = document.createElement(node.nodeName);
2308                if (node.attributes && node.attributes.length > 0) {
2309                    for(var i = 0; i < node.attributes.length; i++) {
2310                        newNode.setAttribute(node.attributes[i].nodeName,
2311                        node.getAttribute(node.attributes[i].nodeName));
2312                    }
2313                }
2314                if (allChildren && node.childNodes &&
2315                node.childNodes.length > 0) {
2316                    for (var i = 0; i < node.childNodes.length; i++) {
2317                        newNode.appendChild(document.importNode(
2318                        node.childNodes[i], allChildren));
2319                    }
2320                }
2321                return newNode;
2322                break;
2323            case document.TEXT_NODE:
2324            case document.CDATA_SECTION_NODE:
2325            case document.COMMENT_NODE:
2326                return document.createTextNode(node.nodeValue);
2327                break;
2328        }
2329    };
2330}
2331
2332/**
2333 *
2334 * Bootstrap self into window.onload and window.onunload
2335 */
2336
2337var oldonunload = window.onunload;
2338
2339window.onunload = function()
2340{
2341        if( oldonunload )
2342        {
2343        oldonunload();
2344    }
2345       
2346        TrophyIM.setPresence('unavailable');
2347}
Note: See TracBrowser for help on using the repository browser.