source: sandbox/jabberit_messenger/trophy_expresso/js/trophyim.js @ 2711

Revision 2711, 53.9 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Implementado a forma de informar um status de message tb pela lista de contatos.

  • Property svn:executable set to *
Line 
1/**
2 *   This program is distributed under the terms of the MIT license.
3 *   Please see the LICENSE file for details.
4 *
5 *   Copyright 2008 Michael Garvin
6 */
7
8var TROPHYIM_BOSH_SERVICE       = "/proxy/ejabberd";  //Change to suit
9
10var TROPHYIM_LOG_LINES          = 200;
11
12var TROPHYIM_LOGLEVEL           = 0; //0=debug, 1=info, 2=warn, 3=error, 4=fatal
13
14var TROPHYIM_VERSION            = "0.3";
15
16var TROPHYIM_RESOURCE           = "/JABBERITWEB";
17
18//Uncomment to make session reattachment work
19//var TROPHYIM_JSON_STORE = "json_store.php";
20
21/** Object: DOMObjects
22 *  This class contains builders for all the DOM objects needed by TrophyIM
23 */
24DOMObjects = {
25    /** Function: xmlParse
26     *  Cross-browser alternative to using innerHTML
27     *  Parses given string, returns valid DOM HTML object
28     *
29     *  Parameters:
30     *    (String) xml - the xml string to parse
31     */
32    xmlParse : function(xmlString) {
33        var xmlObj = this.xmlRender(xmlString);
34        if(xmlObj) {
35            try { //Firefox, Gecko, etc
36                if (this.processor == undefined) {
37                    this.processor = new XSLTProcessor();
38                    this.processor.importStylesheet(this.xmlRender(
39                    '<xsl:stylesheet version="1.0"\
40                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
41                    <xsl:output method="html" indent="yes"/><xsl:template\
42                    match="@*|node()"><xsl:copy><xsl:copy-of\
43                    select="@*|node()"/></xsl:copy></xsl:template>\
44                    </xsl:stylesheet>'));
45                }
46                var htmlObj =
47                this.processor.transformToDocument(xmlObj).documentElement;
48                //Safari has a quirk where it wraps dom elements in <html><body>
49                if (htmlObj.tagName.toLowerCase() == 'html') {
50                    htmlObj = htmlObj.firstChild.firstChild;
51                }
52                return document.importNode(htmlObj, true);
53            } catch(e) {
54                try { //IE is so very very special
55                    var htmlObj = document.importNode(xmlObj.documentElement, true);
56                    if (htmlObj.tagName.toLowerCase() == "div") {
57                        var div_wrapper = document.createElement('div');
58                        div_wrapper.appendChild(htmlObj);
59                        if(div_wrapper.innerHTML) {
60                            div_wrapper.innerHTML = div_wrapper.innerHTML;
61                        }
62                        htmlObj = div_wrapper.firstChild;
63                    }
64                    return htmlObj;
65                } catch(e) {
66                    alert("TrophyIM Error: Cannot add html to page " + e.message);
67                }
68            }
69        }
70    },
71    /** Function: xmlRender
72     *  Uses browser-specific methods to turn given string into xml object
73     *
74     *  Parameters:
75     *    (String) xml - the xml string to parse
76     */
77    xmlRender : function(xmlString) {
78        try {//IE
79            var renderObj = new ActiveXObject("Microsoft.XMLDOM");
80            renderObj.async="false";
81            if(xmlString) {
82                renderObj.loadXML(xmlString);
83            }
84        } catch (e) {
85            try { //Firefox, Gecko, etc
86                if (this.parser == undefined) {
87                    this.parser = new DOMParser();
88                }
89                var renderObj = this.parser.parseFromString(xmlString,
90                "application/xml");
91            } catch(e) {
92                alert("TrophyIM Error: Cannot create new html for page");
93            }
94        }
95
96        return renderObj;
97    },
98    /** Function: getHTML
99     *  Returns named HTML snippet as DOM object
100     *
101     *  Parameters:
102     *    (String) name - name of HTML snippet to retrieve (see HTMLSnippets
103     *    object)
104     */
105    getHTML : function(page)
106        {
107        return this.xmlParse(HTMLSnippets[page]);
108    },
109       
110    /** Function: getScript
111     *  Returns script object with src to given script
112     *
113     *  Parameters:
114     *    (String) script - name of script to put in src attribute of script
115     *    element
116     */
117    getScript : function(script)
118        {
119        var newscript = document.createElement('script');
120        newscript.setAttribute('src', script);
121        newscript.setAttribute('type', 'text/javascript');
122        return newscript;
123    }
124};
125
126/** Object: TrophyIM
127 *
128 *  This is the actual TrophyIM application.  It searches for the
129 *  'trophyimclient' element and inserts itself into that.
130 */
131TrophyIM = {
132   
133        /** AutoConnection
134         *
135         */     
136               
137        autoConnection : { connect : true },
138
139        /** Object: chatHistory
140    *
141    *  Stores chat history (last 10 message) and current presence of active
142    *  chat tabs.  Indexed by jid.
143    */
144       
145        chatHistory : {},
146       
147        /** Constants:
148    *
149    *    (Boolean) stale_roster - roster is stale and needs to be rewritten.
150    */
151       
152        constants : {stale_roster: false},
153       
154        /** PosWindow
155         *
156         */     
157        posWindow : { left : 400, top : 100 }, 
158               
159        /** StatusConnection
160         *
161         */
162
163        statusConn : { connected : false },
164       
165        /** TimeOut Render Roster
166         *
167         *
168         */
169       
170        _timeOut : { renderRoster : null },
171       
172     /** Function: setCookie
173     *
174     *  Sets cookie name/value pair.  Date and path are auto-selected.
175     *
176     *  Parameters:
177     *    (String) name - the name of the cookie variable
178     *    (String) value - the value of the cookie variable
179     */
180   
181        setCookie : function(name, value)
182        {
183        var expire = new Date();
184        expire.setDate(expire.getDate() + 365);
185        document.cookie = name + "=" + value + "; expires=" + expire.toGMTString();
186    },
187   
188        /** Function: delCookie
189     *
190     *  Deletes cookie
191     *
192     *  Parameters:
193     *    (String) name) - the name of the cookie to delete
194     */
195   
196        delCookie : function(name)
197        {
198        var expire = new Date();
199        expire.setDate(expire.getDate() - 365);
200        document.cookie = name + "= ; expires=" + expire.toGMTString();
201        delete TrophyIM.cookies[name];
202    },
203   
204        /** Function: getCookies
205     *
206     *  Retrieves all trophyim cookies into an indexed object.  Inteneded to be
207     *  called once, at which time the app refers to the returned object instead
208     *  of re-parsing the cookie string every time.
209     *
210     *  Each cookie is also re-applied so as to refresh the expiry date.
211     */
212   
213        getCookies : function()
214        {
215        var cObj = {};
216        var cookies = document.cookie.split(';');
217       
218        for(var i = 0 ; i < cookies.length; i++ )
219        {
220                while ( cookies[i].charAt(0) == ' ')
221            {
222                cookies[i] = cookies[i].substring(1,cookies[i].length);
223            }
224               
225            if (cookies[i].substr(0, 8) == "trophyim")
226            {
227                var nvpair = cookies[i].split("=", 2);
228                cObj[nvpair[0]] = nvpair[1];
229                TrophyIM.setCookie(nvpair[0], nvpair[1]);
230            }
231        }
232       
233        return cObj;
234    },
235       
236    /** Function: load
237     *
238     *  This function searches for the trophyimclient div and loads the client
239     *  into it.
240     */
241
242        load : function()
243        {
244                loadscript.setUserCurrent();
245       
246        if (!TrophyIM.statusConn.connected)
247                {
248                        TrophyIM.cookies = TrophyIM.getCookies();
249                       
250                        //Load other .js scripts needed
251                        //document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'js/strophe.min.js'));
252                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'js/strophe.js'));
253                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'js/json2.js')); //Keep this script last
254                        //Wait a second to give scripts time to load
255                        setTimeout("TrophyIM.showLogin()", 500);
256                }
257                else
258                {
259                        loadscript.rosterDiv();
260                }
261   },
262   
263    /** Function: storeData
264     *
265     *  Store all our data in the JSONStore, if it is active
266     */
267     
268   storeData : function()
269   {
270        if ( TrophyIM.connection && TrophyIM.connection.connected )
271                {
272            TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
273            TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
274            TrophyIM.rosterObj.save();
275        }
276    },
277   
278    /**  Function: showlogin
279     *
280     *   This function clears out the IM box and either redisplays the login
281     *   page, or re-attaches to Strophe, preserving the logging div if it
282     *   exists, or creating a new one of we are re-attaching.
283     */
284     
285    showLogin : function()
286        {
287        //JSON is the last script to load, so we wait on it
288        //Added Strophe check too because of bug where it's sometimes missing
289        if (typeof(JSON) != undefined && typeof(Strophe) != undefined)
290        {
291                TrophyIM.JSONStore = new TrophyIMJSONStore();
292               
293            if ( TrophyIM.JSONStore.store_working && TrophyIM.cookies['trophyim_bosh_xid'] )
294            {
295                var xids = TrophyIM.cookies['trophyim_bosh_xid'].split("|");
296                TrophyIM.delCookie('trophyim_bosh_xid');
297                TrophyIM.constants.stale_roster = true;
298                       
299                                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
300                TrophyIM.connection.rawInput    = TrophyIM.rawInput;
301                TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
302                Strophe.log = TrophyIM.log;
303                Strophe.info('Attempting Strophe attach.');
304                TrophyIM.connection.attach(xids[0], xids[1], xids[2], TrophyIM.onConnect);
305                TrophyIM.onConnect(Strophe.Status.CONNECTED);
306            }
307            else
308            {
309                // List Contact
310                                loadscript.rosterDiv();
311                               
312                                if ( loadscript.getUserCurrent() != null )
313                                {
314                                        TrophyIM.login( Base64.decode(loadscript.getUserCurrent().jid), Base64.decode(loadscript.getUserCurrent().password));
315                                }
316                                else
317                                {
318                                        loadscript.loginPage();
319                                }
320            }
321        }
322        else
323        {
324                setTimeout("TrophyIM.showLogin()", 500);
325        }
326    },
327   
328        /** Function: log
329     *
330     *  This function logs the given message in the trophyimlog div
331     *
332     *  Parameter: (String) msg - the message to log
333     */
334   
335    log : function(level, msg)
336    {
337        if (TrophyIM.logging_div && level >= TROPHYIM_LOGLEVEL) {
338            while(TrophyIM.logging_div.childNodes.length > TROPHYIM_LOG_LINES) {
339                TrophyIM.logging_div.removeChild(
340                TrophyIM.logging_div.firstChild);
341            }
342            var msg_div = document.createElement('div');
343            msg_div.className = 'trophyimlogitem';
344            msg_div.appendChild(document.createTextNode(msg));
345            TrophyIM.logging_div.appendChild(msg_div);
346            TrophyIM.logging_div.scrollTop = TrophyIM.logging_div.scrollHeight;
347        }
348    },
349       
350    /** Function: rawInput
351     *
352     *  This logs the packets actually recieved by strophe at the debug level
353     */
354    rawInput : function (data)
355        {
356        Strophe.debug("RECV: " + data);
357    },
358       
359    /** Function: rawInput
360     *
361     *  This logs the packets actually recieved by strophe at the debug level
362     */
363    rawOutput : function (data)
364        {
365        Strophe.debug("SEND: " + data);
366    },
367       
368    /** Function: login
369     *
370     *  This function logs into server using information given on login page.
371     *  Since the login page is where the logging checkbox is, it makes or
372     *  removes the logging div and cookie accordingly.
373     *
374     */
375    login : function()
376        {
377                if (TrophyIM.JSONStore.store_working)
378                {
379                   //In case they never logged out
380            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat', 'chat_history']);
381        }
382
383                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
384        TrophyIM.connection.rawInput    = TrophyIM.rawInput;
385        TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
386        Strophe.log                                     = TrophyIM.log;
387       
388                if ( arguments.length > 0 )
389                {
390                        var barejid = arguments[0];
391                        var password = arguments[1];
392                       
393                        TrophyIM.connection.connect( barejid + TROPHYIM_RESOURCE, password, TrophyIM.onConnect );
394                }
395                else
396                {
397                        var barejid             = document.getElementById('trophyimjid').value
398                        var fulljid             = barejid + TROPHYIM_RESOURCE;
399                        var password    = document.getElementById('trophyimpass').value;
400                        var button              = document.getElementById('trophyimconnect');
401                       
402                        loadscript.setUserCurrent( barejid, password);
403                       
404                        if ( button.value == 'connect' )
405                        {
406                                button.value = 'disconnect';
407                                TrophyIM.connection.connect(fulljid, password, TrophyIM.onConnect);
408                        }
409                        else
410                        {
411                                button.value = 'connect';
412                                TrophyIM.connection.disconnect();
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("Desconectado","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('Disponível','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') )
584                                        TrophyIM.rosterObj.addContact(getAttribute('jid'), getAttribute('ask'), getAttribute('name'), group_array);
585                                else
586                                        TrophyIM.rosterObj.addContact(getAttribute('jid'), getAttribute('subscription'), getAttribute('name'), group_array);
587                        }
588        }
589
590                if ( msg.getAttribute('type') == 'set' )
591                {
592                        var _iq = $iq({type: 'reply', id: msg.getAttribute('id'), to: msg.getAttribute('from')});
593                        TrophyIM.connection.send( _iq.tree());
594        }
595       
596                return true;
597    },
598    /** Function: onPresence
599     *
600     *  Presence handler
601     */
602    onPresence : function(msg)
603        {
604                Strophe.debug("Presence handler");
605        var type                = msg.getAttribute('type') ? msg.getAttribute('type') : 'available';
606        var show                = msg.getElementsByTagName('show').length ? Strophe.getText(msg.getElementsByTagName('show')[0]) : type;
607        var status              = msg.getElementsByTagName('status').length ? Strophe.getText(msg.getElementsByTagName('status')[0]) : '';
608        var priority    = msg.getElementsByTagName('priority').length ? parseInt(Strophe.getText(msg.getElementsByTagName('priority')[0])) : 0;
609
610        TrophyIM.rosterObj.setPresence(msg.getAttribute('from'), priority, show, status);
611               
612        return true;
613    },
614    /** Function: onMessage
615     *
616     *  Message handler
617     */
618    onMessage : function(msg)
619    {
620   
621        var from = msg.getAttribute('from');
622        var type = msg.getAttribute('type');
623        var elems = msg.getElementsByTagName('body');
624
625        if ( (type == 'chat' || type == 'normal') && elems.length > 0 )
626        {
627            var barejid         = Strophe.getBareJidFromJid(from);
628            var jid_lower       = barejid.toLowerCase();
629            var contact         = "";
630            contact                     = barejid.toLowerCase();
631                contact                 = contact.substring(0, contact.indexOf('@'));
632           
633            if( TrophyIM.rosterObj.roster[barejid] )
634            {
635                    if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
636                    {
637                        contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
638                    }
639            }
640
641                var _message = document.createElement("div");
642                _message.innerHTML = Strophe.getText(elems[0]);
643
644                var scripts = _message.getElementsByTagName( 'script' );
645
646                for ( var i = 0; i < scripts.length; i++ )
647                        _message.removeChild( scripts[ i-- ] );
648               
649                _message.innerHTML = _message.innerHTML.replace(/^\s+|\s+$|^\n|\n$/g,"");
650
651                if ( _message.hasChildNodes( ) )
652                {
653                    var message =
654                    {
655                        contact : "<font style='font-weight:bold; color:black;'>" + contact + "</font>",
656                        msg             : _message.innerHTML
657                    };
658       
659                    TrophyIM.makeChat(from); //Make sure we have a chat window
660                    TrophyIM.addMessage(message, jid_lower);
661                }
662        }
663       
664        return true;
665    },
666   
667    /** Function: makeChat
668     *
669     *  Make sure chat window to given fulljid exists, switching chat context to
670     *  given resource
671     */
672     
673    makeChat : function(fulljid)
674    {
675        var barejid             = Strophe.getBareJidFromJid(fulljid);
676        var titleWindow = "";
677       
678        var paramsChatBox =
679        {
680                        'idChatBox'     : barejid + "__chatBox",
681                        'jidTo'                 : barejid,
682                                'path_jabberit' : path_jabberit
683        };
684
685        titleWindow = barejid.toLowerCase();
686                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
687
688        if( TrophyIM.rosterObj.roster[barejid] )
689        {
690            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
691            {
692                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
693            }
694        }
695
696        // Position Top
697        TrophyIM.posWindow.top  = TrophyIM.posWindow.top + 10;
698        if( TrophyIM.posWindow.top > 200 )
699                TrophyIM.posWindow.top  = 100;
700       
701        // Position Left
702        TrophyIM.posWindow.left = TrophyIM.posWindow.left + 5;
703        if( TrophyIM.posWindow.left > 455 )
704                TrophyIM.posWindow.left = 400;
705       
706        var winChatBox =
707        {
708                         id_window              : "window_chat_area_" + barejid,
709                         width                  : 387,
710                         height                 : 365,
711                         top                    : TrophyIM.posWindow.top,
712                         left                   : TrophyIM.posWindow.left,
713                         draggable              : true,
714                         visible                : "display",
715                         resizable              : true,
716                         zindex                 : loadscript.getZIndex(),
717                         title                  : titleWindow,
718                         closeAction    : "hidden",
719                         content                : loadscript.parse("chat_box","chatBox.xsl", paramsChatBox)     
720        }
721       
722        _winBuild(winChatBox);
723
724        // Notification New Message
725        loadscript.notification();
726       
727        // Photo User;
728                loadscript.getPhotoUser(barejid);
729               
730                loadscript.configEvents( document.getElementById( barejid + '__sendBox'),
731                        'onkeyup', function(e)
732                        {
733                                if( e.keyCode == 13 )
734                                {
735                                        TrophyIM.sendMessage( barejid );
736                                        document.getElementById( barejid + '__sendBox').value = '';
737                                        return false;
738                                }
739                        }
740                );
741    },
742
743        /** Function addContacts
744         *
745         *  Parameters:
746         *              (string) jidFrom         
747         *      (string) jidTo
748         *              (string) name
749         *              (string) group   
750         */
751       
752        addContact : function( jidTo, name, group )
753        {
754                // Add Contact
755        var _id = TrophyIM.connection.getUniqueId('add');
756                var newContact = $iq({type: 'set', id: _id });
757                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
758                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
759                        newContact = newContact.c('group').t(group).tree();
760
761                TrophyIM.connection.send(newContact);
762        },
763
764    /** Function: addMessage
765     *
766     *  Parameters:
767     *    (string) msg - the message to add
768     *    (string) jid - the jid of chat box to add the message to.
769     */
770       
771    addMessage : function(msg, jid)
772    {
773        var chatBox             = document.getElementById(jid + "__chatBox");
774        var messageDiv  = document.createElement("div");
775       
776                messageDiv.style.margin = "3px 0px 3px 3px";
777        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
778               
779        chatBox.appendChild(messageDiv);
780        chatBox.scrollTop = chatBox.scrollHeight;
781    },
782       
783    /** Function : renameContact
784     *
785     *
786     */
787   
788    renameContact : function( jid, index )
789    {
790        // Name
791        var name                = TrophyIM.rosterObj.roster[jid].contact.name;
792
793                if(( name = prompt("Informe um novo nome para " + name + "!", name )))
794                        if(( name = name.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
795                                name = "";
796
797                if( name == null || name == "")
798                        name = "";
799               
800        var jidTo = jid
801        var name  = ( name ) ? name : TrophyIM.rosterObj.roster[jid].contact.name;
802        var group = TrophyIM.rosterObj.roster[jid].contact.groups[0];
803       
804        TrophyIM.addContact( jidTo, name, group );
805       
806        document.getElementById('itenContact_' + jid + '_' + index).innerHTML = name;
807    },
808   
809    /** Function : renameGroup
810     *
811     *
812     */
813
814    renameGroup : function( jid, index)
815    {
816        var group               = TrophyIM.rosterObj.roster[jid].contact.groups[0];
817        var presence    = TrophyIM.rosterObj.roster[jid].presence;
818       
819                // Group
820                if(( group = prompt("Informe um novo grupo ou deixe em branco", group )))
821                        if(( group = group.replace(/^\s+|\s+$|^\n|\n$/g,"")) == "" )
822                                group = "";
823
824                if( group == null || group == "")
825                        group = "";
826
827        var jidTo = TrophyIM.rosterObj.roster[jid].contact.jid;
828        var name  = TrophyIM.rosterObj.roster[jid].contact.name;
829                var group = ( group ) ? group : TrophyIM.rosterObj.roster[jid].contact.groups[0];
830
831                TrophyIM.rosterObj.removeContact( jid );
832               
833                TrophyIM.addContact( jidTo, name, group );
834       
835                document.getElementById("JabberIMRoster").innerHTML = "";
836               
837        TrophyIM.renderRoster();
838       
839        setTimeout(function()
840        {
841                for( var i in presence )
842                {
843                        if ( presence[ i ].constructor == Function )
844                                continue;
845                               
846                        TrophyIM.rosterObj.setPresence( jid, presence[i].priority, presence[i].show, presence[i].status);
847                }
848        },500);
849    },
850   
851    /** Function: removeContact
852     *
853     *  Parameters:
854     *          (string) jidTo
855     */
856   
857    removeContact : function(jidTo, indexTo)
858    {
859        var divItenContact       = null;
860        var spanShow             = null;
861       
862        if( ( divItenContact = document.getElementById('itenContact_' + jidTo + '_' + indexTo )))
863        {       
864                spanShow = document.getElementById('span_show_itenContact_' + jidTo + '_' + indexTo )
865               
866                spanShow.parentNode.removeChild(spanShow);
867               
868                loadscript.removeGroup( divItenContact.parentNode );
869               
870                divItenContact.parentNode.removeChild(divItenContact);
871
872                // Remove Contact
873                        var _id = TrophyIM.connection.getUniqueId();   
874                var delContact  = $iq({type: 'set', id: _id})
875                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
876                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
877
878                TrophyIM.connection.send( delContact );                 
879                       
880                // Remove Contact       
881                var _id = TrophyIM.connection.getUniqueId();
882                var _delContact_ = $iq({type: 'set', id: _id})
883                        _delContact_ = _delContact_.c('query').attrs({xmlns : 'jabber:iq:private'});
884                        _delContact_ = _delContact_.c('storage').attrs({xmlns : 'storage:metacontacts'}).tree();
885
886                TrophyIM.connection.send( _delContact_ );       
887        }
888    },
889   
890    /** Function: renderRoster
891     *
892     *  Renders roster, looking only for jids flagged by setPresence as having
893     *  changed.
894     */
895   
896        renderRoster : function()
897        {
898                var roster_div = document.getElementById('JabberIMRoster');
899               
900                if( roster_div )
901                {
902                        var users = new Array();
903                       
904                        var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
905                       
906                        if( loading_gif.style.display == "block" )
907                                loading_gif.style.display = "none";
908                               
909                        for( var user in TrophyIM.rosterObj.roster )
910                        {
911                                if ( TrophyIM.rosterObj.roster[ user ].constructor == Function )
912                                        continue;
913
914                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
915                        }
916
917                        users.sort();
918                       
919                        var groups              = new Array();
920                        var flagGeral   = false;
921                       
922                        for (var group in TrophyIM.rosterObj.groups)
923                        {
924                                if ( TrophyIM.rosterObj.groups[ group ].constructor == Function )
925                                        continue;
926                               
927                                if( group )
928                                        groups[groups.length] = group;
929                               
930                                if( group == "Geral" )
931                                        flagGeral = true;
932            }
933           
934                        if( !flagGeral && users.length > 0 )
935                                groups[groups.length] = "Geral";
936                               
937                        groups.sort();
938                       
939                        for ( var i = 0; i < groups.length; i++ )
940                        {
941                                TrophyIM.renderGroups( groups[i] , roster_div );       
942                        }
943                       
944                        TrophyIM.renderItensGroup( users, roster_div );
945                }
946                       
947                TrophyIM._timeOut.renderRoster = setTimeout("TrophyIM.renderRoster()", 1000 );         
948        },
949       
950    /** Function: renderGroups
951     *
952     *
953     */
954       
955        renderGroups: function( nameGroup, element )
956        {
957                var _addGroup = function()
958                {
959                        var _nameGroup  = nameGroup;
960                        var _element    = element;
961
962                        var paramsGroup =
963                        {
964                                'nameGroup'     : _nameGroup,
965                                'path_jabberit' : path_jabberit
966                        }
967                       
968                        _element.innerHTML += loadscript.parse("group","groups.xsl", paramsGroup);
969                }
970
971                if( !element.hasChildNodes() )
972                {
973                        _addGroup();
974                }
975                else
976                {
977                        var _NodeChild  = element.firstChild;
978                        var flagAdd             = false;
979                       
980                        while( _NodeChild )
981                        {
982                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
983                                {
984                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
985                                        {
986                                                flagAdd = true;
987                                        }
988                                }
989                               
990                                _NodeChild = _NodeChild.nextSibling;
991                        }
992
993                        if( !flagAdd )
994                        {
995                                _addGroup();
996                        }
997                }
998        },
999
1000    /** Function: renderItensGroup
1001     *
1002     *
1003     */
1004
1005        renderItensGroup : function( users, element )
1006        {
1007                var addItem = function()
1008                {
1009                        if( arguments.length > 0 )
1010                        {
1011                                var objContact  = arguments[0];
1012                                var group               = arguments[1];
1013                                var element             = arguments[2];
1014                                var index               = arguments[3];
1015                                var showOffline = loadscript.getShowContactsOffline();
1016                               
1017                                var itensJid    = document.getElementById( 'itenContact_' + objContact.contact.jid + '_' + index );
1018
1019                                if( itensJid == null )
1020                                {
1021                                        // Name
1022                                        var nameContact = "";                                   
1023                                       
1024                                        if ( objContact.contact.name )
1025                                                nameContact = objContact.contact.name;
1026                                        else
1027                                        {
1028                                                nameContact = objContact.contact.jid;
1029                                                nameContact = nameContact.substring(0, nameContact.indexOf('@'));
1030                                        }
1031                                       
1032                                        // Presence e Status
1033                                        var presence            = "unavailable";
1034                                        var status                      = "";
1035                                        var statusDisplay       = "none";
1036                                       
1037                                        if (objContact.presence)
1038                                        {
1039                                                for (var resource in objContact.presence)
1040                                                {
1041                                                        if ( objContact.presence[resource].constructor == Function )
1042                                                                continue;
1043
1044                                                        if( objContact.presence[resource].show != 'invisible' )
1045                                                                presence = objContact.presence[resource].show;
1046
1047                                                        if( objContact.contact.subscription != "both")
1048                                                                presence = 'subscription';
1049                                                       
1050                                                        if( objContact.presence[resource].status )
1051                                                        {
1052                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1053                                                                statusDisplay   = "block";
1054                                                        }
1055                                                }
1056                                        }
1057                                       
1058                                        var paramsContact =
1059                                        {
1060                                                divDisplay              : "block",
1061                                                id                              : 'itenContact_' + objContact.contact.jid + '_' + index ,
1062                                                index                   : ((index == 0 ) ? "0" : index),
1063                                                jid                             : objContact.contact.jid,
1064                                                nameContact     : nameContact,
1065                                                path_jabberit   : path_jabberit,
1066                                                presence                : presence,
1067                                                spanDisplay             : statusDisplay,
1068                                                status                  : status,
1069                                                statusColor             : "black",
1070                                                subscription    : objContact.contact.subscription
1071                                        }
1072                                       
1073                                        // Authorization       
1074                                        if( objContact.contact.subscription != "both" )
1075                                        {
1076                                               
1077                                                switch(objContact.contact.subscription)
1078                                                {
1079                                                        case "none" :
1080                                                               
1081                                                                paramsContact.status            = " (( PEDIR AUTORIZAÇAO ! )) ";
1082                                                                paramsContact.statusColor       = "red";
1083                                                                break;
1084       
1085                                                        case "to" :
1086                                                               
1087                                                                paramsContact.status            = " (( CONTATO PEDE AUTORIZAÇÃO ! )) ";
1088                                                                paramsContact.statusColor       = "orange";
1089                                                                break;
1090       
1091                                                        case "from" :
1092                                                               
1093                                                                paramsContact.status            = " (( AUTORIZAR ? )) ";
1094                                                                paramsContact.statusColor       = "green";
1095                                                                break;
1096                                                               
1097                                                        case "subscribe" :
1098                                                               
1099                                                                paramsContact.status            = " (( AUTORIZAÇÃO ENVIADA ! )) ";
1100                                                                paramsContact.statusColor       = "red";       
1101                                                                break;
1102
1103                                                        case "not-in-roster" :
1104                                                               
1105                                                                paramsContact.status            = " (( QUERO ADICIONÁ-LO(A) ! POSSO ? )) ";
1106                                                                paramsContact.statusColor       = "orange";     
1107                                                                break;
1108                                                               
1109                                                        default:
1110                                                                paramsContact.status = " ( " + objContact.contact.subscription + " ) ";
1111                                                }
1112                                        }
1113                                       
1114                                        if( group != "")
1115                                        {
1116                                                var _NodeChild          = element.firstChild;
1117                                               
1118                                                while( _NodeChild )
1119                                                {
1120                                                        if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
1121                                                        {
1122                                                                if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
1123                                                                {
1124                                                                        _NodeChild.innerHTML += loadscript.parse("itens_group", "itensGroup.xsl", paramsContact);
1125                                                                }
1126                                                        }
1127
1128                                                        _NodeChild = _NodeChild.nextSibling;
1129                                                }
1130                                        }       
1131                                }
1132                                else
1133                                {
1134
1135                                        // Presence e Status
1136                                        var presence            = "unavailable";
1137                                        var status                      = "";
1138                                        var statusColor         = "black";
1139                                        var statusDisplay       = "none";
1140                                       
1141                                        if ( objContact.presence )
1142                                        {
1143                                                for ( var resource in objContact.presence )
1144                                                {
1145                                                        if ( objContact.presence[resource].constructor == Function )
1146                                                                continue;
1147
1148                                                        if( objContact.presence[resource].show != 'invisible' )
1149                                                                presence = objContact.presence[resource].show;
1150
1151                                                        if( objContact.contact.subscription != "both")
1152                                                                presence = 'subscription';
1153                                                       
1154                                                        if( objContact.presence[resource].status )
1155                                                        {
1156                                                                status = " ( " + objContact.presence[resource].status + " ) ";
1157                                                                statusDisplay   = "block";
1158                                                        }
1159                                                }       
1160                                        }
1161                                               
1162                                        var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
1163                                                is_open = is_open.indexOf("arrow_down.gif");
1164                                       
1165                                        // Authorization       
1166                                        if( objContact.contact.subscription != "both" )
1167                                        {
1168                                                switch(objContact.contact.subscription)
1169                                                {
1170                                                        case "none" :
1171                                                               
1172                                                                status          = " (( PEDIR AUTORIZAÇAO ! )) ";
1173                                                                statusColor     = "red";
1174                                                                break;
1175       
1176                                                        case "to" :
1177                                                               
1178                                                                status          = " (( CONTATO PEDE AUTORIZAÇÃO ! )) ";
1179                                                                statusColor     = "orange";
1180                                                                break;
1181       
1182                                                        case "from" :
1183                                                               
1184                                                                status          = " (( AUTORIZAR ? )) ";
1185                                                                statusColor = "green";
1186                                                                break;
1187                                                               
1188                                                        case "subscribe" :
1189                                                               
1190                                                                status          = " (( AUTORIZAÇÃO ENVIADA ! )) ";
1191                                                                statusColor     = "red";       
1192                                                                break;
1193
1194                                                        case "not-in-roster" :
1195                                                               
1196                                                                status          = " (( QUERO ADICIONÁ-LO(A) ! POSSO ? )) ";
1197                                                                statusColor     = "orange";     
1198                                                                break;
1199                                                               
1200                                                        default:
1201                                                                status = " ( " + objContact.contact.subscription + " ) ";
1202                                                }
1203
1204                                                statusDisplay = "block";
1205                                        }
1206                                       
1207                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ) )
1208                                        {
1209                                                /*if( is_open > 0 )
1210                                                {
1211                                                        style.display   = statusDisplay;
1212                                                        style.color             = statusColor;
1213                                                        innerHTML               = status;
1214                                                }*/
1215
1216                                                if( presence == "unavailable" && !showOffline )
1217                                                {
1218                                                        style.display = "none";
1219                                                }
1220                                                else
1221                                                {
1222                                                        if( is_open > 0 )
1223                                                        {
1224                                                                style.display   = statusDisplay;
1225                                                                style.color             = statusColor;
1226                                                                innerHTML               = status;
1227                                                        }
1228                                                }
1229                                        }
1230                                       
1231                                        if( presence == "unavailable" && !showOffline )
1232                                                itensJid.style.display = "none";
1233                                        else
1234                                        {
1235                                                if( is_open > 0 )
1236                                                {
1237                                                        itensJid.style.display = "block";
1238                                                }
1239                                        }
1240                                       
1241                                        itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif') no-repeat center left";
1242                                }
1243
1244                                // Contact OffLine
1245                                if( !objContact.presence && !showOffline )
1246                                {
1247                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ))
1248                                        {
1249                                                style.display   = "none";
1250                                        }
1251
1252                                        with ( document.getElementById('itenContact_' + objContact.contact.jid + '_' + index ) )
1253                                        {
1254                                                style.display   = "none";
1255                                        }
1256                                }
1257                        }
1258                }
1259               
1260                for( var i = 0 ; i < users.length; i++ )
1261                {
1262                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != Base64.decode(loadscript.getUserCurrent().jid) )
1263                        {
1264                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1265                                {
1266                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1267                                       
1268                                        if( groups.length > 0 )
1269                                        {
1270                                                for( var j = 0; j < groups.length; j++ )
1271                                                {
1272                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element, j );
1273                                                }
1274                                        }
1275                                        else
1276                                        {
1277                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1278                                        }
1279                                }
1280                                else
1281                                {
1282                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1283                                }
1284                        }
1285                }       
1286        },
1287
1288    /** Function: rosterClick
1289     *
1290     *  Handles actions when a roster item is clicked
1291     */
1292   
1293        rosterClick : function(fulljid)
1294        {
1295        TrophyIM.makeChat(fulljid);
1296    },
1297
1298
1299        /** Function SetAutorization
1300         *
1301         */
1302
1303        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1304        {
1305        var _id = TrophyIM.connection.getUniqueId();
1306       
1307        TrophyIM.connection.send($pres( ).attrs( {to: jidTo, from: jidFrom, type: _typeSubscription, id: _id}).tree());
1308        },
1309   
1310        /** Function: setPresence
1311     *
1312     */
1313
1314        setPresence : function( _type )
1315        {
1316                if( _type != 'status')
1317                {
1318                        if( _type == "unavailable")
1319                        {
1320                                var loading_gif = document.getElementById("JabberIMRosterLoadingGif");
1321                               
1322                                if( TrophyIM._timeOut.renderRoster != null )
1323                                        clearTimeout(TrophyIM._timeOut.renderRoster);
1324                               
1325                                TrophyIM.connection.send($pres({type : _type}).tree());
1326                               
1327                                for( var i = 0; i < TrophyIM.connection._requests.length; i++ )
1328                        {
1329                                if( TrophyIM.connection._requests[i] )
1330                                        TrophyIM.connection._removeRequest(TrophyIM.connection._requests[i]);
1331                        }
1332                               
1333                                TrophyIM.logout();
1334                               
1335                        loadscript.clrAllContacts();
1336                       
1337                        delete TrophyIM.rosterObj.roster;
1338                        delete TrophyIM.rosterObj.groups;
1339                       
1340                        setTimeout(function()
1341                        {
1342                                        if( loading_gif.style.display == "block" )
1343                                                loading_gif.style.display = "none";
1344                        }, 1000);
1345                        }
1346                        else
1347                        {
1348                                if( !TrophyIM.autoConnection.connect )
1349                                {
1350                                        TrophyIM.autoConnection.connect = true;
1351                                        TrophyIM.load();
1352                                }
1353                                else
1354                                {
1355                                        if( loadscript.getStatusMessage() != "" )
1356                                        {
1357                                                var _presence = $pres( );
1358                                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _type ) );
1359                                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( loadscript.getStatusMessage() ));
1360                                               
1361                                                TrophyIM.connection.send( _presence.tree() );
1362                                        }
1363                                        else
1364                                        {
1365                                                TrophyIM.connection.send($pres( ).c('show').t(_type).tree());
1366                                        }
1367                                }
1368                        }
1369                }
1370                else
1371                {
1372                        var _show       = "available";
1373                        var _status     = "";
1374                       
1375                        if( arguments.length < 2 )
1376                        {
1377                                if( loadscript.getStatusMessage() != "" )
1378                                        _status = prompt("Digite sua mensagem !!!", loadscript.getStatusMessage());
1379                                else
1380                                        _status = prompt("Digite sua mensagem !!!");
1381                               
1382                                var _divStatus = document.getElementById("JabberIMStatusMessage");
1383                               
1384                                if( ( _status = _status.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "")
1385                                        _divStatus.firstChild.innerHTML = "( " + _status + " )";
1386                        }
1387                        else
1388                        {
1389                                _status = arguments[1];
1390                        }
1391
1392                        for(var resource in TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence )
1393                        {
1394                        if ( TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[ resource ].constructor == Function )
1395                                continue;
1396                       
1397                                if ( TROPHYIM_RESOURCE === ("/" + resource) )
1398                                        _show = TrophyIM.rosterObj.roster[Base64.decode(loadscript.getUserCurrent().jid)].presence[resource].show;
1399                        }
1400
1401                        var _presence = $pres( );
1402                        _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1403                        _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1404                       
1405                        TrophyIM.connection.send( _presence.tree() );
1406                }
1407        },
1408       
1409        /** Function: sendMessage
1410     *
1411     *  Send message from chat input to user
1412     */
1413     
1414    sendMessage : function()
1415    {
1416
1417        if( arguments.length > 0 )
1418        {
1419                var jidTo = arguments[0];
1420                var message_input = document.getElementById(jidTo + "__sendBox").value;
1421           
1422                if( ( message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "" )
1423                {
1424                        // Send Message
1425                        TrophyIM.connection.send($msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'}).c('body').t(message_input).tree());
1426                       
1427                        var message =
1428                        {
1429                                        contact : "<font style='font-weight:bold; color:red;'>" + "Eu" + "</font>",
1430                                        msg : message_input
1431                        }
1432                       
1433                        // Add Message in chatBox;
1434                        TrophyIM.addMessage( message, jidTo);
1435                                document.getElementById(jidTo + "__sendBox").value = "";
1436                                document.getElementById(jidTo + "__sendBox").focus();
1437                }
1438        }
1439    }
1440};
1441
1442/** Class: TrophyIMRoster
1443 *
1444 *
1445 *  This object stores the roster and presence info for the TrophyIMClient
1446 *
1447 *  roster[jid_lower]['contact']
1448 *  roster[jid_lower]['presence'][resource]
1449 */
1450function TrophyIMRoster()
1451{
1452    /** Constants: internal arrays
1453     *    (Object) roster - the actual roster/presence information
1454     *    (Object) groups - list of current groups in the roster
1455     *    (Array) changes - array of jids with presence changes
1456     */
1457    if (TrophyIM.JSONStore.store_working)
1458        {
1459        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1460        this.roster = (data['roster'] != null) ? data['roster'] : {};
1461        this.groups = (data['groups'] != null) ? data['groups'] : {};
1462    }
1463        else
1464        {
1465        this.roster = {};
1466        this.groups = {};
1467    }
1468    this.changes = new Array();
1469   
1470        if (TrophyIM.constants.stale_roster)
1471        {
1472        for (var jid in this.roster)
1473                {
1474                        this.changes[this.changes.length] = jid;
1475        }
1476    }
1477
1478        /** Function: addChange
1479         *
1480         *  Adds given jid to this.changes, keeping this.changes sorted and
1481         *  preventing duplicates.
1482         *
1483         *  Parameters
1484         *    (String) jid : jid to add to this.changes
1485         */
1486         
1487        this.addChange = function(jid)
1488        {
1489                for (var c = 0; c < this.changes.length; c++)
1490                {
1491                        if (this.changes[c] == jid)
1492                        {
1493                                return;
1494                        }
1495                }
1496               
1497                this.changes[this.changes.length] = jid;
1498               
1499                this.changes.sort();
1500        }
1501       
1502    /** Function: addContact
1503     *
1504     *  Adds given contact to roster
1505     *
1506     *  Parameters:
1507     *    (String) jid - bare jid
1508     *    (String) subscription - subscription attribute for contact
1509     *    (String) name - name attribute for contact
1510     *    (Array)  groups - array of groups contact is member of
1511     */
1512   
1513        this.addContact = function(jid, subscription, name, groups )
1514        {
1515        if( subscription !== "remove" )
1516        {
1517                var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
1518                var jid_lower   = jid.toLowerCase();
1519       
1520                        if ( this.roster[jid_lower] )
1521                        {
1522                    this.roster[jid_lower]['contact'] = contact;
1523                }
1524                        else
1525                        {
1526                    this.roster[jid_lower] = {contact:contact};
1527                }
1528
1529                        groups = groups ? groups : [''];
1530               
1531                        for ( var g = 0; g < groups.length; g++ )
1532                        {
1533                                if ( !this.groups[groups[g]] )
1534                                {
1535                        this.groups[groups[g]] = {};
1536                    }
1537                   
1538                                this.groups[groups[g]][jid_lower] = jid_lower;
1539                }
1540        }
1541        else
1542        {
1543                this.removeContact(jid);
1544        }
1545    }
1546   
1547    /** Function: getContact
1548     *
1549     *  Returns contact entry for given jid
1550     *
1551     *  Parameter: (String) jid - jid to return
1552     */
1553     
1554    this.getContact = function(jid)
1555        {
1556        if (this.roster[jid.toLowerCase()])
1557                {
1558            return this.roster[jid.toLowerCase()]['contact'];
1559        }
1560    }
1561
1562   /** Function: getPresence
1563        *
1564        *  Returns best presence for given jid as Array(resource, priority, show,
1565        *  status)
1566        *
1567        *  Parameter: (String) fulljid - jid to return best presence for
1568        */
1569         
1570        this.getPresence = function(fulljid)
1571        {
1572                var jid = Strophe.getBareJidFromJid(fulljid);
1573                var current = null;
1574                   
1575                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
1576                {
1577                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
1578                        {
1579                        if ( this.roster[jid.toLowerCase()]['presence'][ resource ].constructor == Function )
1580                                continue;
1581                       
1582                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1583                                if (current == null)
1584                                {
1585                                        current = presence
1586                                }
1587                                else
1588                                {
1589                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1590                                        || presence['show'] == "available") || (current['show'] != "chat" ||
1591                                        current['show'] != "available")))
1592                                        {
1593                                                current = presence
1594                                        }
1595                                }
1596                        }
1597                }
1598                return current;
1599        }
1600
1601        /** Function: groupHasChanges
1602         *
1603         *  Returns true if current group has members in this.changes
1604         *
1605         *  Parameters:
1606         *    (String) group - name of group to check
1607         */
1608         
1609        this.groupHasChanges = function(group)
1610        {
1611                for (var c = 0; c < this.changes.length; c++)
1612                {
1613                        if (this.groups[group][this.changes[c]])
1614                        {
1615                                return true;
1616                        }
1617                }
1618                return false;
1619        }
1620       
1621        /** Function removeContact
1622         *
1623         * Parameters
1624         *       (String) jid           
1625         */
1626         
1627         this.removeContact = function(jid)
1628         {
1629                if( this.roster[ jid ] )
1630                {
1631                        var groups = this.roster[ jid ].contact.groups;
1632                       
1633                        if( groups )
1634                        {
1635                                for ( var i = 0; i < groups.length; i++ )
1636                                {
1637                                        delete this.groups[ groups[ i ] ][ jid ];
1638                                }
1639       
1640                                for ( var i = 0; i < groups.length; i++ )
1641                                {
1642                                        var contacts = 0;
1643                                        for ( var contact in this.groups[ groups[ i ] ] )
1644                                        {
1645                                        if ( this.groups[ groups[ i ] ][ contact ].constructor == Function )
1646                                                continue;
1647                                       
1648                                                contacts++;
1649                                        }
1650               
1651                                        if ( ! contacts )
1652                                                delete this.groups[ groups[ i ] ];
1653                                }
1654                        }
1655       
1656                        // Delete Object roster
1657                        if( this.roster[jid] )
1658                                delete this.roster[jid];
1659                }
1660         }
1661         
1662    /** Function: setPresence
1663     *
1664     *  Sets presence
1665     *
1666     *  Parameters:
1667     *    (String) fulljid: full jid with presence
1668     *    (Integer) priority: priority attribute from presence
1669     *    (String) show: show attribute from presence
1670     *    (String) status: status attribute from presence
1671     */
1672   
1673        this.setPresence = function(fulljid, priority, show, status)
1674        {
1675                var barejid             = Strophe.getBareJidFromJid(fulljid);
1676        var resource    = Strophe.getResourceFromJid(fulljid);
1677        var jid_lower   = barejid.toLowerCase();
1678       
1679                if( show != 'unavailable')
1680                {
1681            if (!this.roster[jid_lower])
1682                        {
1683                this.addContact(barejid, 'not-in-roster');
1684            }
1685            var presence =
1686                        {
1687                resource:resource, priority:priority, show:show, status:status
1688            }
1689           
1690                        if (!this.roster[jid_lower]['presence'])
1691                        {
1692                this.roster[jid_lower]['presence'] = {};
1693            }
1694            this.roster[jid_lower]['presence'][resource] = presence;
1695        }
1696                else if (this.roster[jid_lower] && this.roster[jid_lower]['presence'] && this.roster[jid_lower]['presence'][resource])
1697                {
1698            delete this.roster[jid_lower]['presence'][resource];
1699        }
1700       
1701                this.addChange(jid_lower);
1702    }
1703
1704        /** Fuction: save
1705         *
1706         *  Saves roster data to JSON store
1707         */
1708       
1709        this.save = function()
1710        {
1711                if (TrophyIM.JSONStore.store_working)
1712                {
1713                        TrophyIM.JSONStore.setData({roster:this.roster,
1714                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
1715                        chat_history:TrophyIM.chatHistory});
1716                }
1717        }
1718
1719}
1720/** Class: TrophyIMJSONStore
1721 *
1722 *
1723 *  This object is the mechanism by which TrophyIM stores and retrieves its
1724 *  variables from the url provided by TROPHYIM_JSON_STORE
1725 *
1726 */
1727function TrophyIMJSONStore() {
1728    this.store_working = false;
1729    /** Function _newXHR
1730     *
1731     *  Set up new cross-browser xmlhttprequest object
1732     *
1733     *  Parameters:
1734     *    (function) handler = what to set onreadystatechange to
1735     */
1736     this._newXHR = function (handler) {
1737        var xhr = null;
1738        if (window.XMLHttpRequest) {
1739            xhr = new XMLHttpRequest();
1740            if (xhr.overrideMimeType) {
1741            xhr.overrideMimeType("text/xml");
1742            }
1743        } else if (window.ActiveXObject) {
1744            xhr = new ActiveXObject("Microsoft.XMLHTTP");
1745        }
1746        return xhr;
1747    }
1748    /** Function getData
1749     *  Gets data from JSONStore
1750     *
1751     *  Parameters:
1752     *    (Array) vars = Variables to get from JSON store
1753     *
1754     *  Returns:
1755     *    Object with variables indexed by names given in parameter 'vars'
1756     */
1757    this.getData = function(vars) {
1758        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1759            Strophe.debug("Retrieving JSONStore data");
1760            var xhr = this._newXHR();
1761            var getdata = "get=" + vars.join(",");
1762            try {
1763                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1764            } catch (e) {
1765                Strophe.error("JSONStore open failed.");
1766                return false;
1767            }
1768            xhr.setRequestHeader('Content-type',
1769            'application/x-www-form-urlencoded');
1770            xhr.setRequestHeader('Content-length', getdata.length);
1771            xhr.send(getdata);
1772            if (xhr.readyState == 4 && xhr.status == 200) {
1773                try {
1774                    var dataObj = JSON.parse(xhr.responseText);
1775                    return this.emptyFix(dataObj);
1776                } catch(e) {
1777                    Strophe.error("Could not parse JSONStore response" +
1778                    xhr.responseText);
1779                    return false;
1780                }
1781            } else {
1782                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1783                return false;
1784            }
1785        }
1786    }
1787    /** Function emptyFix
1788     *    Fix for bugs in external JSON implementations such as
1789     *    http://bugs.php.net/bug.php?id=41504.
1790     *    A.K.A. Don't use PHP, people.
1791     */
1792    this.emptyFix = function(obj) {
1793        if (typeof(obj) == "object") {
1794            for (var i in obj) {
1795                        if ( obj[i].constructor == Function )
1796                                continue;
1797                       
1798                if (i == '_empty_') {
1799                    obj[""] = this.emptyFix(obj['_empty_']);
1800                    delete obj['_empty_'];
1801                } else {
1802                    obj[i] = this.emptyFix(obj[i]);
1803                }
1804            }
1805        }
1806        return obj
1807    }
1808    /** Function delData
1809     *    Deletes data from JSONStore
1810     *
1811     *  Parameters:
1812     *    (Array) vars  = Variables to delete from JSON store
1813     *
1814     *  Returns:
1815     *    Status of delete attempt.
1816     */
1817    this.delData = function(vars) {
1818        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1819            Strophe.debug("Retrieving JSONStore data");
1820            var xhr = this._newXHR();
1821            var deldata = "del=" + vars.join(",");
1822            try {
1823                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1824            } catch (e) {
1825                Strophe.error("JSONStore open failed.");
1826                return false;
1827            }
1828            xhr.setRequestHeader('Content-type',
1829            'application/x-www-form-urlencoded');
1830            xhr.setRequestHeader('Content-length', deldata.length);
1831            xhr.send(deldata);
1832            if (xhr.readyState == 4 && xhr.status == 200) {
1833                try {
1834                    var dataObj = JSON.parse(xhr.responseText);
1835                    return dataObj;
1836                } catch(e) {
1837                    Strophe.error("Could not parse JSONStore response");
1838                    return false;
1839                }
1840            } else {
1841                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1842                return false;
1843            }
1844        }
1845    }
1846    /** Function setData
1847     *    Stores data in JSONStore, overwriting values if they exist
1848     *
1849     *  Parameters:
1850     *    (Object) vars : Object containing named vars to store ({name: value,
1851     *    othername: othervalue})
1852     *
1853     *  Returns:
1854     *    Status of storage attempt
1855     */
1856    this.setData = function(vars) {
1857        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1858            Strophe.debug("Storing JSONStore data");
1859            var senddata = "set=" + JSON.stringify(vars);
1860            var xhr = this._newXHR();
1861            try {
1862                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1863            } catch (e) {
1864                Strophe.error("JSONStore open failed.");
1865                return false;
1866            }
1867            xhr.setRequestHeader('Content-type',
1868            'application/x-www-form-urlencoded');
1869            xhr.setRequestHeader('Content-length', senddata.length);
1870            xhr.send(senddata);
1871            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
1872            "OK") {
1873                return true;
1874            } else {
1875                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1876                return false;
1877            }
1878        }
1879    }
1880    var testData = true;
1881    if (this.setData({testData:testData})) {
1882        var testResult = this.getData(['testData']);
1883        if (testResult && testResult['testData'] == true) {
1884            this.store_working = true;
1885        }
1886    }
1887}
1888/** Constants: Node types
1889 *
1890 * Implementations of constants that IE doesn't have, but we need.
1891 */
1892if (document.ELEMENT_NODE == null) {
1893    document.ELEMENT_NODE = 1;
1894    document.ATTRIBUTE_NODE = 2;
1895    document.TEXT_NODE = 3;
1896    document.CDATA_SECTION_NODE = 4;
1897    document.ENTITY_REFERENCE_NODE = 5;
1898    document.ENTITY_NODE = 6;
1899    document.PROCESSING_INSTRUCTION_NODE = 7;
1900    document.COMMENT_NODE = 8;
1901    document.DOCUMENT_NODE = 9;
1902    document.DOCUMENT_TYPE_NODE = 10;
1903    document.DOCUMENT_FRAGMENT_NODE = 11;
1904    document.NOTATION_NODE = 12;
1905}
1906
1907/** Function: importNode
1908 *
1909 *  document.importNode implementation for IE, which doesn't have importNode
1910 *
1911 *  Parameters:
1912 *    (Object) node - dom object
1913 *    (Boolean) allChildren - import node's children too
1914 */
1915if (!document.importNode) {
1916    document.importNode = function(node, allChildren) {
1917        switch (node.nodeType) {
1918            case document.ELEMENT_NODE:
1919                var newNode = document.createElement(node.nodeName);
1920                if (node.attributes && node.attributes.length > 0) {
1921                    for(var i = 0; i < node.attributes.length; i++) {
1922                        newNode.setAttribute(node.attributes[i].nodeName,
1923                        node.getAttribute(node.attributes[i].nodeName));
1924                    }
1925                }
1926                if (allChildren && node.childNodes &&
1927                node.childNodes.length > 0) {
1928                    for (var i = 0; i < node.childNodes.length; i++) {
1929                        newNode.appendChild(document.importNode(
1930                        node.childNodes[i], allChildren));
1931                    }
1932                }
1933                return newNode;
1934                break;
1935            case document.TEXT_NODE:
1936            case document.CDATA_SECTION_NODE:
1937            case document.COMMENT_NODE:
1938                return document.createTextNode(node.nodeValue);
1939                break;
1940        }
1941    };
1942}
1943
1944/**
1945 *
1946 * Bootstrap self into window.onload and window.onunload
1947 */
1948
1949var oldonunload = window.onunload;
1950
1951window.onunload = function()
1952{
1953        if( oldonunload )
1954        {
1955        oldonunload();
1956    }
1957       
1958        TrophyIM.setPresence('unavailable');
1959}
Note: See TracBrowser for help on using the repository browser.