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

Revision 3107, 67.8 KB checked in by alexandrecorreia, 14 years ago (diff)

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

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