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

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