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

Revision 3264, 67.6 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #1333 - Correcao do titulo das salas de bate papo quando existem caracteres especiais

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