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

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

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

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