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

Revision 3308, 67.7 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Na adicao de contatos ja esta sendo enviado o aceite do convite.

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