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

Revision 3127, 67.4 KB checked in by alexandrecorreia, 14 years ago (diff)

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

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