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

Revision 2471, 44.4 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Correção da lista de contatos para a leitura de um contato em varios grupos.

  • 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(
67                    "TrophyIM Error: Cannot add html to page" + e.message);
68                }
69            }
70        }
71    },
72    /** Function: xmlRender
73     *  Uses browser-specific methods to turn given string into xml object
74     *
75     *  Parameters:
76     *    (String) xml - the xml string to parse
77     */
78    xmlRender : function(xmlString) {
79        try {//IE
80            var renderObj = new ActiveXObject("Microsoft.XMLDOM");
81            renderObj.async="false";
82            if(xmlString) {
83                renderObj.loadXML(xmlString);
84            }
85        } catch (e) {
86            try { //Firefox, Gecko, etc
87                if (this.parser == undefined) {
88                    this.parser = new DOMParser();
89                }
90                var renderObj = this.parser.parseFromString(xmlString,
91                "application/xml");
92            } catch(e) {
93                alert("TrophyIM Error: Cannot create new html for page");
94            }
95        }
96
97        return renderObj;
98    },
99    /** Function: getHTML
100     *  Returns named HTML snippet as DOM object
101     *
102     *  Parameters:
103     *    (String) name - name of HTML snippet to retrieve (see HTMLSnippets
104     *    object)
105     */
106    getHTML : function(page)
107        {
108        return this.xmlParse(HTMLSnippets[page]);
109    },
110       
111    /** Function: getScript
112     *  Returns script object with src to given script
113     *
114     *  Parameters:
115     *    (String) script - name of script to put in src attribute of script
116     *    element
117     */
118    getScript : function(script)
119        {
120        var newscript = document.createElement('script');
121        newscript.setAttribute('src', script);
122        newscript.setAttribute('type', 'text/javascript');
123        return newscript;
124    }
125};
126
127/** Object: TrophyIM
128 *
129 *  This is the actual TrophyIM application.  It searches for the
130 *  'trophyimclient' element and inserts itself into that.
131 */
132TrophyIM = {
133   
134        statusConn : { connected : false },
135       
136        /** Constants:
137     *
138     *    (Boolean) stale_roster - roster is stale and needs to be rewritten.
139     */
140    constants : {stale_roster: false},
141   
142        /** Object: chatHistory
143     *
144     *  Stores chat history (last 10 message) and current presence of active
145     *  chat tabs.  Indexed by jid.
146     */
147    chatHistory : {},
148   
149    /** Object: activeChats
150     *
151     *  This object stores the currently active chats.
152     */
153    activeChats : {current: null, divs: {}},
154   
155     /** Function: setCookie
156     *
157     *  Sets cookie name/value pair.  Date and path are auto-selected.
158     *
159     *  Parameters:
160     *    (String) name - the name of the cookie variable
161     *    (String) value - the value of the cookie variable
162     */
163   
164        setCookie : function(name, value)
165        {
166        var expire = new Date();
167        expire.setDate(expire.getDate() + 365);
168        document.cookie = name + "=" + value + "; expires=" + expire.toGMTString();
169    },
170   
171        /** Function: delCookie
172     *
173     *  Deletes cookie
174     *
175     *  Parameters:
176     *    (String) name) - the name of the cookie to delete
177     */
178   
179        delCookie : function(name)
180        {
181        var expire = new Date();
182        expire.setDate(expire.getDate() - 365);
183        document.cookie = name + "= ; expires=" + expire.toGMTString();
184        delete TrophyIM.cookies[name];
185    },
186   
187        /** Function: getCookies
188     *
189     *  Retrieves all trophyim cookies into an indexed object.  Inteneded to be
190     *  called once, at which time the app refers to the returned object instead
191     *  of re-parsing the cookie string every time.
192     *
193     *  Each cookie is also re-applied so as to refresh the expiry date.
194     */
195   
196        getCookies : function()
197        {
198        var cObj = {};
199        var cookies = document.cookie.split(';');
200        for (var c in cookies)
201        {
202            while (cookies[c].charAt(0)==' ')
203            {
204                cookies[c] = cookies[c].substring(1,cookies[c].length);
205            }
206            if (cookies[c].substr(0, 8) == "trophyim")
207            {
208                var nvpair = cookies[c].split("=", 2);
209                cObj[nvpair[0]] = nvpair[1];
210                TrophyIM.setCookie(nvpair[0], nvpair[1]);
211            }
212        }
213       
214        return cObj;
215    },
216       
217    /** Function: load
218     *
219     *  This function searches for the trophyimclient div and loads the client
220     *  into it.
221     */
222
223        load : function()
224        {
225                if (!TrophyIM.statusConn.connected)
226                {
227                        TrophyIM.cookies = TrophyIM.getCookies();
228                       
229                        //Load other .js scripts needed
230                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'strophejs/strophe.js'));
231                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'strophejs/md5.js'));
232                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'strophejs/sha1.js'));
233                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'strophejs/b64.js'));
234                        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript(path_jabberit + 'js/json2.js')); //Keep this script last
235                        //Wait a second to give scripts time to load
236                        setTimeout("TrophyIM.showLogin()", 500);
237                }
238                else
239                {
240                        loadIM.rosterDiv();
241                }
242   },
243   
244    /** Function: storeData
245     *
246     *  Store all our data in the JSONStore, if it is active
247     */
248     
249   storeData : function()
250   {
251        if ( TrophyIM.connection && TrophyIM.connection.connected )
252                {
253            TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
254            TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
255            TrophyIM.rosterObj.save();
256        }
257    },
258   
259    /**  Function: showlogin
260     *
261     *   This function clears out the IM box and either redisplays the login
262     *   page, or re-attaches to Strophe, preserving the logging div if it
263     *   exists, or creating a new one of we are re-attaching.
264     */
265     
266    showLogin : function()
267        {
268        //JSON is the last script to load, so we wait on it
269        //Added Strophe check too because of bug where it's sometimes missing
270        if (typeof(JSON) != undefined && typeof(Strophe) != undefined)
271        {
272                TrophyIM.JSONStore = new TrophyIMJSONStore();
273               
274            if ( TrophyIM.JSONStore.store_working && TrophyIM.cookies['trophyim_bosh_xid'] )
275            {
276                var xids = TrophyIM.cookies['trophyim_bosh_xid'].split("|");
277                TrophyIM.delCookie('trophyim_bosh_xid');
278                TrophyIM.constants.stale_roster = true;
279                       
280                                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
281                TrophyIM.connection.rawInput    = TrophyIM.rawInput;
282                TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
283                Strophe.log = TrophyIM.log;
284                Strophe.info('Attempting Strophe attach.');
285                TrophyIM.connection.attach(xids[0], xids[1], xids[2], TrophyIM.onConnect);
286                TrophyIM.onConnect(Strophe.Status.CONNECTED);
287            }
288            else
289            {
290                                // List Contact
291                                loadIM.rosterDiv();
292                               
293                                if ( loadIM.getUserCurrent() != null )
294                                {
295                                        TrophyIM.login( loadIM.getUserCurrent().jid, loadIM.getUserCurrent().password );
296                                }
297                                else
298                                {
299                                        loadIM.loginPage();
300                                }
301            }
302        }
303        else
304        {
305                setTimeout("TrophyIM.showLogin()", 500);
306        }
307    },
308   
309        /** Function: log
310     *
311     *  This function logs the given message in the trophyimlog div
312     *
313     *  Parameter: (String) msg - the message to log
314     */
315   
316    log : function(level, msg)
317    {
318        if (TrophyIM.logging_div && level >= TROPHYIM_LOGLEVEL) {
319            while(TrophyIM.logging_div.childNodes.length > TROPHYIM_LOG_LINES) {
320                TrophyIM.logging_div.removeChild(
321                TrophyIM.logging_div.firstChild);
322            }
323            var msg_div = document.createElement('div');
324            msg_div.className = 'trophyimlogitem';
325            msg_div.appendChild(document.createTextNode(msg));
326            TrophyIM.logging_div.appendChild(msg_div);
327            TrophyIM.logging_div.scrollTop = TrophyIM.logging_div.scrollHeight;
328        }
329    },
330       
331    /** Function: rawInput
332     *
333     *  This logs the packets actually recieved by strophe at the debug level
334     */
335    rawInput : function (data)
336        {
337        Strophe.debug("RECV: " + data);
338    },
339       
340    /** Function: rawInput
341     *
342     *  This logs the packets actually recieved by strophe at the debug level
343     */
344    rawOutput : function (data)
345        {
346        Strophe.debug("SEND: " + data);
347    },
348       
349    /** Function: login
350     *
351     *  This function logs into server using information given on login page.
352     *  Since the login page is where the logging checkbox is, it makes or
353     *  removes the logging div and cookie accordingly.
354     *
355     */
356    login : function()
357        {
358                if (TrophyIM.JSONStore.store_working)
359                {
360                   //In case they never logged out
361            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat', 'chat_history']);
362        }
363
364                TrophyIM.connection                             = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
365        TrophyIM.connection.rawInput    = TrophyIM.rawInput;
366        TrophyIM.connection.rawOutput   = TrophyIM.rawOutput;
367        Strophe.log                                     = TrophyIM.log;
368       
369                if ( arguments.length > 0 )
370                {
371                        var barejid = arguments[0];
372                        var password = arguments[1];
373                       
374                        TrophyIM.connection.connect(barejid + TROPHYIM_RESOURCE, password, TrophyIM.onConnect);
375                }
376                else
377                {
378                        var barejid             = document.getElementById('trophyimjid').value
379                        var fulljid             = barejid + TROPHYIM_RESOURCE;
380                        var password    = document.getElementById('trophyimpass').value;
381                        var button              = document.getElementById('trophyimconnect');
382                       
383                        loadIM.setUserCurrent( barejid, password);
384                       
385                        if ( button.value == 'connect' )
386                        {
387                                button.value = 'disconnect';
388                                TrophyIM.connection.connect(fulljid, password, TrophyIM.onConnect);
389                        }
390                        else
391                        {
392                                button.value = 'connect';
393                                TrophyIM.connection.disconnect();
394                        }
395                }
396
397                TrophyIM.setCookie('trophyimjid', barejid);
398
399    },
400       
401    /** Function: logout
402     *
403     *  Logs into fresh session through Strophe, purging any old data.
404     */
405    logout : function()
406        {
407        TrophyIM.delCookie('trophyim_bosh_xid');
408        delete TrophyIM['cookies']['trophyim_bosh_xid'];
409       
410                if (TrophyIM.JSONStore.store_working)
411                {
412            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat', 'chat_history']);
413        }
414       
415                for (var chat in TrophyIM.activeChats['divs'])
416                {
417            delete TrophyIM.activeChats['divs'][chat];
418        }
419               
420        TrophyIM.activeChats = {current: null, divs: {}},
421        TrophyIM.connection.disconnect();
422        TrophyIM.showLogin();
423               
424    },
425       
426    /** Function onConnect
427     *
428     *  Callback given to Strophe upon connection to BOSH proxy.
429     */
430    onConnect : function(status)
431        {
432                if (status == Strophe.Status.CONNECTING)
433                {
434                        Strophe.info('Strophe is connecting.');
435        }
436               
437                if (status == Strophe.Status.CONNFAIL)
438                {
439                        Strophe.info('Strophe failed to connect.');
440            TrophyIM.delCookie('trophyim_bosh_xid');
441            TrophyIM.showLogin();
442        }
443               
444                if (status == Strophe.Status.DISCONNECTING)
445                {
446                        Strophe.info('Strophe is disconnecting.');
447        }
448               
449                if (status == Strophe.Status.DISCONNECTED)
450                {
451                        Strophe.info('Strophe is disconnected.');
452            TrophyIM.delCookie('trophyim_bosh_xid');
453            TrophyIM.showLogin();
454        }
455               
456                if (status == Strophe.Status.CONNECTED)
457                {
458                        loadIM.setStatusJabber('Disponível','available');
459                        TrophyIM.statusConn.connected = true;
460            TrophyIM.showClient();
461                        Strophe.info('Strophe is connected.');
462        }
463    },
464
465    /** Function: showClient
466     *
467     *  This clears out the main div and puts in the main client.  It also
468     *  registers all the handlers for Strophe to call in the client.
469     */
470    showClient : function()
471        {
472        TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
473        TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
474               
475        TrophyIM.rosterObj = new TrophyIMRoster();
476        TrophyIM.connection.addHandler(TrophyIM.onVersion, Strophe.NS.VERSION, 'iq', null, null, null);
477        TrophyIM.connection.addHandler(TrophyIM.onRoster, Strophe.NS.ROSTER, 'iq', null, null, null);
478        TrophyIM.connection.addHandler(TrophyIM.onPresence, null, 'presence', null, null, null);
479        TrophyIM.connection.addHandler(TrophyIM.onMessage, null, 'message', null, null,  null);
480       
481                //Get roster then announce presence.
482        TrophyIM.connection.send($iq({type: 'get', xmlns: Strophe.NS.CLIENT}).c('query', {xmlns: Strophe.NS.ROSTER}).tree());
483        TrophyIM.connection.send($pres().tree());
484                setTimeout("TrophyIM.renderRoster()", 1000);
485    },
486       
487    /** Function: clearClient
488     *
489     *  Clears out client div, preserving and returning existing logging_div if
490     *  one exists
491     */
492     
493    clearClient : function()
494    {
495        if(TrophyIM.logging_div)
496        {
497            var logging_div = TrophyIM.client_div.removeChild(document.getElementById('trophyimlog'));
498        }
499        else
500        {
501            var logging_div = null;
502        }
503       
504        while(TrophyIM.client_div.childNodes.length > 0)
505        {
506            TrophyIM.client_div.removeChild(TrophyIM.client_div.firstChild);
507        }
508       
509        return logging_div;
510    },
511   
512    /** Function: onVersion
513     *
514     *  jabber:iq:version query handler
515     */
516     
517    onVersion : function(msg)
518    {
519        Strophe.debug("Version handler");
520        if (msg.getAttribute('type') == 'get')
521        {
522            var from = msg.getAttribute('from');
523            var to = msg.getAttribute('to');
524            var id = msg.getAttribute('id');
525            var reply = $iq({type: 'result', to: from, from: to, id: id}).c('query',
526            {name: "TrophyIM", version: TROPHYIM_VERSION, os:
527            "Javascript-capable browser"});
528            TrophyIM.connection.send(reply.tree());
529        }
530        return true;
531    },
532   
533    /** Function: onRoster
534     *
535     *  Roster iq handler
536     */
537   
538    onRoster : function(msg)
539        {
540        var roster_items = msg.firstChild.getElementsByTagName('item');
541               
542                for (var i = 0; i < roster_items.length; i++)
543                {
544                        with(roster_items[i])
545                        {
546                                var groups              = getElementsByTagName('group');       
547                                var group_array = [];
548                               
549                                for( var g = 0 ; g < groups.length; g++ )
550                                {
551                                        if( groups[g].hasChildNodes() )
552                                                group_array[group_array.length] = groups[g].firstChild.nodeValue;
553                                }
554
555                                TrophyIM.rosterObj.addContact(getAttribute('jid'), getAttribute('subscription'), getAttribute('name'), group_array);
556                        }
557                       
558                        /*
559                        var groups = roster_items[i].getElementsByTagName('group');
560           
561                        var group_array = new Array();
562           
563                        for (var g = 0; g < groups.length; g++)
564                        {
565                                if( groups[g].firstChild != null )
566                                        group_array[group_array.length] = groups[g].firstChild.nodeValue;
567            }
568                       
569                        with ( roster_items[i] )
570                        {
571                                alert(getAttribute('jid') + "\n" + getAttribute('subscription') + "\n" + getAttribute('name'));
572                                TrophyIM.rosterObj.addContact(getAttribute('jid'), getAttribute('subscription'), getAttribute('name'), group_array);
573                        }
574                        */
575        }
576
577                if ( msg.getAttribute('type') == 'set' )
578                {
579                        var _iq = $iq({type: 'reply', id: msg.getAttribute('id'), to: msg.getAttribute('from')});
580                        TrophyIM.connection.send( _iq.tree());
581        }
582       
583                return true;
584    },
585    /** Function: onPresence
586     *
587     *  Presence handler
588     */
589    onPresence : function(msg)
590        {
591                Strophe.debug("Presence handler");
592        var type                = msg.getAttribute('type') ? msg.getAttribute('type') : 'available';
593        var show                = msg.getElementsByTagName('show').length ? Strophe.getText(msg.getElementsByTagName('show')[0]) : type;
594        var status              = msg.getElementsByTagName('status').length ? Strophe.getText(msg.getElementsByTagName('status')[0]) : '';
595        var priority    = msg.getElementsByTagName('priority').length ? parseInt(Strophe.getText(msg.getElementsByTagName('priority')[0])) : 0;
596
597        TrophyIM.rosterObj.setPresence(msg.getAttribute('from'), priority, show, status);
598               
599        return true;
600    },
601    /** Function: onMessage
602     *
603     *  Message handler
604     */
605    onMessage : function(msg)
606    {
607   
608        var from = msg.getAttribute('from');
609        var type = msg.getAttribute('type');
610        var elems = msg.getElementsByTagName('body');
611
612        if ( (type == 'chat' || type == 'normal') && elems.length > 0 )
613        {
614            var barejid         = Strophe.getBareJidFromJid(from);
615            var jid_lower       = barejid.toLowerCase();
616            var contact         = "";
617               
618            if( TrophyIM.rosterObj.roster[barejid] )
619            {
620                    if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
621                    {
622                        contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
623                    }
624            }
625            else
626            {
627                contact = barejid.toLowerCase();
628                contact = contact.substring(0, contact.indexOf('@'));
629            }   
630           
631            var message =
632            {
633                contact : "<font style='font-weight:bold; color:black;'>" + contact + "</font>",
634                msg             : Strophe.getText(elems[0])     
635            };
636
637            TrophyIM.makeChat(from); //Make sure we have a chat window
638            TrophyIM.addMessage(message, jid_lower);
639        }
640       
641        return true;
642    },
643   
644    /** Function: makeChat
645     *
646     *  Make sure chat window to given fulljid exists, switching chat context to
647     *  given resource
648     */
649     
650    makeChat : function(fulljid)
651    {
652        var barejid             = Strophe.getBareJidFromJid(fulljid);
653        var titleWindow = "";
654       
655        var paramsChatBox =
656        {
657                        'idChatBox'     : barejid + "__chatBox",
658                        'jidTo'                 : barejid,
659                                'path_jabberit' : path_jabberit
660        };
661       
662        if( TrophyIM.rosterObj.roster[barejid] )
663        {
664            if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
665            {
666                titleWindow = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
667            }
668        }
669        else
670        {
671                titleWindow = barejid.toLowerCase();
672                titleWindow = contact.substring(0, contact.indexOf('@'));
673        }       
674
675        var winChatBox =
676        {
677                         id_window              : "window_chat_area_" + barejid,
678                         width                  : 387,
679                         height                 : 365,
680                         top                    : 100,
681                         left                   : 400,
682                         draggable              : true,
683                         visible                : "display",
684                         resizable              : true,
685                         zindex                 : loadIM.getZIndex(),
686                         title                  : titleWindow,
687                         closeAction    : "hidden",
688                         content                : loadIM.parse("chat_box","chatBox.xsl", paramsChatBox)
689        }
690       
691        _winBuild(winChatBox);
692               
693                loadIM.configEvents( document.getElementById( barejid + '__sendBox'),
694                        'onkeyup', function(e)
695                        {
696                                if( e.keyCode == 13 )
697                                {
698                                        TrophyIM.sendMessage( barejid );
699                                        document.getElementById( barejid + '__sendBox').value = '';
700                                        return false;
701                                }
702                        }
703                );
704    },
705
706        /** Function addContacts
707         *
708         *  Parameters:
709         *              (string) jidFrom         
710         *      (string) jidTo
711         *              (string) name
712         *              (string) group   
713         */
714       
715        addContact : function( jidFrom, jidTo, name, group )
716        {
717                // Set Presence
718        var newPresence = $pres({from: jidFrom, to: jidTo, type: 'subscribe'}).tree();
719                       
720                TrophyIM.connection.send(newPresence);
721       
722        // Add Contact
723        var _id = TrophyIM.connection.getUniqueId();
724                var newContact = $iq({type: 'set', id: _id });
725                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
726                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
727                        newContact = newContact.c('group').t(group).tree();
728
729                TrophyIM.connection.send(newContact);
730        },
731
732    /** Function: addMessage
733     *
734     *  Parameters:
735     *    (string) msg - the message to add
736     *    (string) jid - the jid of chat box to add the message to.
737     */
738       
739    addMessage : function(msg, jid)
740    {
741        var chatBox             = document.getElementById(jid + "__chatBox");
742        var messageDiv  = document.createElement("div");
743       
744                messageDiv.style.margin = "3px 0px 3px 3px";
745        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
746               
747        chatBox.appendChild(messageDiv);
748        chatBox.scrollTop = chatBox.scrollHeight;
749    },
750       
751    /** Function: removeContact
752     *
753     *  Parameters:
754     *          (string) jidTo
755     */
756   
757    removeContact : function(jidTo)
758    {
759        var divItenContact = null;
760       
761        if( ( divItenContact = document.getElementById('itenContact_' + jidTo)))
762        {       
763                loadIM.removeGroup( divItenContact.parentNode );
764               
765                divItenContact.parentNode.removeChild(divItenContact);
766               
767                // Remove Contact
768                        var _id = TrophyIM.connection.getUniqueId();   
769                var delContact  = $iq({type: 'set', id: _id})
770                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
771                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
772               
773                TrophyIM.connection.send(delContact);
774        }
775    },
776   
777    /** Function: renderRoster
778     *
779     *  Renders roster, looking only for jids flagged by setPresence as having
780     *  changed.
781     */
782   
783        renderRoster : function()
784        {
785                var roster_div = document.getElementById('JabberIMRoster');
786               
787                if( roster_div )
788                {
789                        var users = new Array();
790                       
791                        for( var user in TrophyIM.rosterObj.roster )
792                        {
793                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
794                        }
795
796                        users.sort();
797                       
798                        var groups              = new Array();
799                        var flagGeral   = false;
800                       
801                        for (var group in TrophyIM.rosterObj.groups)
802                        {
803                                if( group )
804                                        groups[groups.length] = group;
805                               
806                                if( group == "Geral" )
807                                        flagGeral = true;
808            }
809           
810                        if( !flagGeral )
811                                groups[groups.length] = "Geral";
812                               
813                        groups.sort();
814                       
815                        for ( var i = 0; i < groups.length; i++ )
816                        {
817                                TrophyIM.renderGroups( groups[i] , roster_div );       
818                        }
819                       
820                        TrophyIM.renderItensGroup( users, roster_div );
821                }
822                       
823                setTimeout("TrophyIM.renderRoster()", 1000 );           
824        },
825       
826    /** Function: renderGroups
827     *
828     *
829     */
830       
831        renderGroups: function( nameGroup, element )
832        {
833                var _addGroup = function()
834                {
835                        var _nameGroup  = nameGroup;
836                        var _element    = element;
837
838                        var paramsGroup =
839                        {
840                                'nameGroup'     : _nameGroup,
841                                'path_jabberit' : path_jabberit
842                        }
843                       
844                        _element.innerHTML += loadIM.parse("group","groups.xsl", paramsGroup);
845                }
846
847                if( !element.hasChildNodes() )
848                {
849                        _addGroup();
850                }
851                else
852                {
853                        var _NodeChild  = element.firstChild;
854                        var flagAdd             = false;
855                       
856                        while( _NodeChild )
857                        {
858                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
859                                {
860                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
861                                        {
862                                                flagAdd = true;
863                                        }
864                                }
865                               
866                                _NodeChild = _NodeChild.nextSibling;
867                        }
868
869                        if( !flagAdd )
870                        {
871                                _addGroup();
872                        }
873                }
874        },
875
876    /** Function: renderItensGroup
877     *
878     *
879     */
880
881        renderItensGroup : function( users, element )
882        {
883                var addItem = function()
884                {
885                        if( arguments.length > 0 )
886                        {
887                                var objContact  = arguments[0];
888                                var group               = arguments[1];
889                                var element             = arguments[2];
890                                var index               = arguments[3];
891                               
892                                var itensJid    = document.getElementById( 'itenContact_' + objContact.contact.jid + '_' + index );
893                               
894                                if( itensJid == null )
895                                {
896                                        // Name
897                                        var nameContact = "";                                   
898                                       
899                                        if ( objContact.contact.name )
900                                                nameContact = objContact.contact.name;
901                                        else
902                                        {
903                                                nameContact = objContact.contact.jid;
904                                                nameContact = nameContact.substring(0, nameContact.indexOf('@'));
905                                        }
906                                       
907                                        // Presence e Status
908                                        var presence            = "unavailable";
909                                        var status                      = "";
910                                        var statusDisplay       = "none";
911                                       
912                                        if (objContact.presence)
913                                        {
914                                                for (var resource in objContact.presence)
915                                                {
916                                                        if( objContact.presence[resource].show != 'invisible' )
917                                                                presence = objContact.presence[resource].show;
918
919                                                        if( objContact.presence[resource].status )
920                                                        {
921                                                                status                  = " ( " + objContact.presence[resource].status + " ) ";
922                                                                statusDisplay   = "block";
923                                                        }
924                                                }
925                                        }
926                                       
927                                        var paramsContact =
928                                        {
929                                                'nameContact'   : nameContact,
930                                                'jid'                   : objContact.contact.jid,       
931                                                'id'                    : 'itenContact_' + objContact.contact.jid + '_' + index ,
932                                                'index'                 : index,
933                                                'path_jabberit' : path_jabberit,
934                                                'presence'              : presence,
935                                                'status'                : status,
936                                                'statusDisplay' : statusDisplay
937                                        }
938                                       
939                                        if( group != "")
940                                        {
941                                                var _NodeChild          = element.firstChild;
942                                               
943                                                while( _NodeChild )
944                                                {
945                                                        if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
946                                                        {
947                                                                if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
948                                                                {
949                                                                        _NodeChild.innerHTML += loadIM.parse("itens_group", "itensGroup.xsl", paramsContact);
950                                                                }
951                                                        }
952
953                                                        _NodeChild = _NodeChild.nextSibling;
954                                                }
955                                        }       
956                                }
957                                else
958                                {
959                                        // Presence e Status
960                                        var presence            = "unavailable";
961                                        var status                      = "";
962                                        var statusDisplay       = "none";
963                                       
964                                        if (objContact.presence)
965                                        {
966                                                for ( var resource in objContact.presence )
967                                                {
968                                                        presence = objContact.presence[resource].show;
969                                                       
970                                                        if( objContact.presence[resource].status )
971                                                        {
972                                                                status                  = " ( " + objContact.presence[resource].status + " ) ";
973                                                                statusDisplay   = "block";
974                                                        }
975                                                }       
976                                        }
977                                               
978                                        var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
979                                                is_open = is_open.indexOf("arrow_down.gif");
980                                       
981                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ) )
982                                        {
983                                                if( is_open > 0 )
984                                                {
985                                                        style.display   = statusDisplay;
986                                                        innerHTML               = status;
987                                                }
988                                        }
989                                       
990                                        itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif')no-repeat center left";
991                                }
992                               
993                        }
994                }
995               
996                for( var i = 0 ; i < users.length; i++ )
997                {
998                        if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
999                        {
1000                                var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1001                               
1002                                if( groups.length > 0 )
1003                                {
1004                                        for( var j = 0; j < groups.length; j++ )
1005                                                addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element, j );
1006                                }
1007                                else
1008                                {
1009                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1010                                }
1011                        }
1012                        else
1013                        {
1014                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1015                        }
1016                }       
1017        },
1018
1019    /** Function: rosterClick
1020     *
1021     *  Handles actions when a roster item is clicked
1022     */
1023   
1024        rosterClick : function(fulljid)
1025        {
1026        TrophyIM.makeChat(fulljid);
1027    },
1028
1029
1030        /** Function SetAutorization
1031         *
1032         */
1033
1034        setAutorization : function( jid )
1035        {
1036           TrophyIM.connection.send($pres( ).attrs( {to: jid, from: loadIM.getUserCurrent().jid, type:'subscribed'}).tree());
1037        },
1038   
1039        /** Function: setPresence
1040     *
1041     */
1042
1043        setPresence : function( show )
1044        {
1045                TrophyIM.connection.send($pres( ).c('show').t(show).tree());
1046        },
1047       
1048        /** Function: sendMessage
1049     *
1050     *  Send message from chat input to user
1051     */
1052     
1053    sendMessage : function()
1054    {
1055
1056        if( arguments.length > 0 )
1057        {
1058                var jidTo = arguments[0];
1059                var message_input = document.getElementById(jidTo + "__sendBox").value;
1060           
1061                if( ( message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "" )
1062                {
1063                        // Send Message
1064                        TrophyIM.connection.send($msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'}).c('body').t(message_input).tree());
1065                       
1066                        var message =
1067                        {
1068                                        contact : "<font style='font-weight:bold; color:red;'>" + "Eu" + "</font>",
1069                                        msg : message_input
1070                        }
1071                       
1072                        // Add Message in chatBox;
1073                        TrophyIM.addMessage( message, jidTo);
1074                                document.getElementById(jidTo + "__sendBox").value = "";
1075                                document.getElementById(jidTo + "__sendBox").focus();
1076                }
1077        }
1078    }
1079};
1080
1081/** Class: TrophyIMRoster
1082 *
1083 *
1084 *  This object stores the roster and presence info for the TrophyIMClient
1085 *
1086 *  roster[jid_lower]['contact']
1087 *  roster[jid_lower]['presence'][resource]
1088 */
1089function TrophyIMRoster()
1090{
1091    /** Constants: internal arrays
1092     *    (Object) roster - the actual roster/presence information
1093     *    (Object) groups - list of current groups in the roster
1094     *    (Array) changes - array of jids with presence changes
1095     */
1096    if (TrophyIM.JSONStore.store_working)
1097        {
1098        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1099        this.roster = (data['roster'] != null) ? data['roster'] : {};
1100        this.groups = (data['groups'] != null) ? data['groups'] : {};
1101    }
1102        else
1103        {
1104        this.roster = {};
1105        this.groups = {};
1106    }
1107    this.changes = new Array();
1108   
1109        if (TrophyIM.constants.stale_roster)
1110        {
1111        for (var jid in this.roster)
1112                {
1113                        this.changes[this.changes.length] = jid;
1114        }
1115    }
1116
1117        /** Function: addChange
1118         *
1119         *  Adds given jid to this.changes, keeping this.changes sorted and
1120         *  preventing duplicates.
1121         *
1122         *  Parameters
1123         *    (String) jid : jid to add to this.changes
1124         */
1125         
1126        this.addChange = function(jid)
1127        {
1128                for (var c = 0; c < this.changes.length; c++)
1129                {
1130                        if (this.changes[c] == jid)
1131                        {
1132                                return;
1133                        }
1134                }
1135               
1136                this.changes[this.changes.length] = jid;
1137               
1138                this.changes.sort();
1139        }
1140       
1141    /** Function: addContact
1142     *
1143     *  Adds given contact to roster
1144     *
1145     *  Parameters:
1146     *    (String) jid - bare jid
1147     *    (String) subscription - subscription attribute for contact
1148     *    (String) name - name attribute for contact
1149     *    (Array)  groups - array of groups contact is member of
1150     */
1151   
1152        this.addContact = function(jid, subscription, name, groups )
1153        {
1154        if( jid != loadIM.getUserCurrent().jid )
1155        {
1156                if( subscription !== "remove" )
1157                {
1158                        var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
1159                        var jid_lower   = jid.toLowerCase();
1160               
1161                                if ( this.roster[jid_lower] )
1162                                {
1163                            this.roster[jid_lower]['contact'] = contact;
1164                        }
1165                                else
1166                                {
1167                            this.roster[jid_lower] = {contact:contact};
1168                        }
1169               
1170                                groups = groups ? groups : [''];
1171                       
1172                                for ( var g = 0; g < groups.length; g++ )
1173                                {
1174                                        if ( !this.groups[groups[g]] )
1175                                        {
1176                                this.groups[groups[g]] = {};
1177                            }
1178                           
1179                                        this.groups[groups[g]][jid_lower] = jid_lower;
1180                        }
1181                }
1182                else
1183                {
1184                        this.removeContact(jid);
1185                }
1186        }
1187    }
1188   
1189    /** Function: getContact
1190     *
1191     *  Returns contact entry for given jid
1192     *
1193     *  Parameter: (String) jid - jid to return
1194     */
1195     
1196    this.getContact = function(jid)
1197        {
1198        if (this.roster[jid.toLowerCase()])
1199                {
1200            return this.roster[jid.toLowerCase()]['contact'];
1201        }
1202    }
1203
1204   /** Function: getPresence
1205        *
1206        *  Returns best presence for given jid as Array(resource, priority, show,
1207        *  status)
1208        *
1209        *  Parameter: (String) fulljid - jid to return best presence for
1210        */
1211         
1212        this.getPresence = function(fulljid)
1213        {
1214                var jid = Strophe.getBareJidFromJid(fulljid);
1215                var current = null;
1216                   
1217                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
1218                {
1219                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
1220                        {
1221                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1222                                if (current == null)
1223                                {
1224                                        current = presence
1225                                }
1226                                else
1227                                {
1228                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1229                                        || presence['show'] == "available") || (current['show'] != "chat" ||
1230                                        current['show'] != "available")))
1231                                        {
1232                                                current = presence
1233                                        }
1234                                }
1235                        }
1236                }
1237                return current;
1238        }
1239
1240        /** Function: groupHasChanges
1241         *
1242         *  Returns true if current group has members in this.changes
1243         *
1244         *  Parameters:
1245         *    (String) group - name of group to check
1246         */
1247         
1248        this.groupHasChanges = function(group)
1249        {
1250                for (var c = 0; c < this.changes.length; c++)
1251                {
1252                        if (this.groups[group][this.changes[c]])
1253                        {
1254                                return true;
1255                        }
1256                }
1257                return false;
1258        }
1259       
1260        /** Function removeContact
1261         *
1262         * Parameters
1263         *       (String) jid           
1264         */
1265         
1266         this.removeContact = function(jid)
1267         {
1268                var groups = this.roster[ jid ].contact.groups;
1269               
1270                for ( var i = 0; i < groups.length; i++ )
1271                {
1272                        delete this.groups[ groups[ i ] ][ jid ];
1273                }
1274
1275                for ( var i = 0; i < groups.length; i++ )
1276                {
1277                        var contacts = 0;
1278                        for ( var contact in this.groups[ groups[ i ] ] )
1279                                contacts++;
1280
1281                        if ( ! contacts )
1282                                delete this.groups[ groups[ i ] ];
1283                }
1284
1285                // Delete Object roster
1286                if( this.roster[jid] )
1287                        delete this.roster[jid];               
1288         }
1289         
1290    /** Function: setPresence
1291     *
1292     *  Sets presence
1293     *
1294     *  Parameters:
1295     *    (String) fulljid: full jid with presence
1296     *    (Integer) priority: priority attribute from presence
1297     *    (String) show: show attribute from presence
1298     *    (String) status: status attribute from presence
1299     */
1300   
1301        this.setPresence = function(fulljid, priority, show, status)
1302        {
1303                var barejid = Strophe.getBareJidFromJid(fulljid);
1304        var resource = Strophe.getResourceFromJid(fulljid);
1305        var jid_lower = barejid.toLowerCase();
1306       
1307        if( barejid != loadIM.getUserCurrent().jid )
1308        {
1309                        if( show != 'unavailable')
1310                        {
1311                    if (!this.roster[jid_lower])
1312                                {
1313                        this.addContact(barejid, 'not-in-roster');
1314                    }
1315                    var presence =
1316                                {
1317                        resource:resource, priority:priority, show:show, status:status
1318                    }
1319                   
1320                                if (!this.roster[jid_lower]['presence'])
1321                                {
1322                        this.roster[jid_lower]['presence'] = {}
1323                    }
1324                    this.roster[jid_lower]['presence'][resource] = presence
1325                }
1326                        else if (this.roster[jid_lower] && this.roster[jid_lower]['presence'] && this.roster[jid_lower]['presence'][resource])
1327                        {
1328                    delete this.roster[jid_lower]['presence'][resource];
1329                }
1330               
1331                        this.addChange(jid_lower);
1332               
1333                        if (TrophyIM.activeChats['divs'][jid_lower])
1334                        {
1335                    TrophyIM.setTabPresence(jid_lower, TrophyIM.activeChats['divs'][jid_lower]['tab']);
1336                }
1337        }
1338    }
1339
1340        /** Fuction: save
1341         *
1342         *  Saves roster data to JSON store
1343         */
1344       
1345        this.save = function()
1346        {
1347                if (TrophyIM.JSONStore.store_working)
1348                {
1349                        TrophyIM.JSONStore.setData({roster:this.roster,
1350                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
1351                        chat_history:TrophyIM.chatHistory});
1352                }
1353        }
1354
1355}
1356/** Class: TrophyIMJSONStore
1357 *
1358 *
1359 *  This object is the mechanism by which TrophyIM stores and retrieves its
1360 *  variables from the url provided by TROPHYIM_JSON_STORE
1361 *
1362 */
1363function TrophyIMJSONStore() {
1364    this.store_working = false;
1365    /** Function _newXHR
1366     *
1367     *  Set up new cross-browser xmlhttprequest object
1368     *
1369     *  Parameters:
1370     *    (function) handler = what to set onreadystatechange to
1371     */
1372     this._newXHR = function (handler) {
1373        var xhr = null;
1374        if (window.XMLHttpRequest) {
1375            xhr = new XMLHttpRequest();
1376            if (xhr.overrideMimeType) {
1377            xhr.overrideMimeType("text/xml");
1378            }
1379        } else if (window.ActiveXObject) {
1380            xhr = new ActiveXObject("Microsoft.XMLHTTP");
1381        }
1382        return xhr;
1383    }
1384    /** Function getData
1385     *  Gets data from JSONStore
1386     *
1387     *  Parameters:
1388     *    (Array) vars = Variables to get from JSON store
1389     *
1390     *  Returns:
1391     *    Object with variables indexed by names given in parameter 'vars'
1392     */
1393    this.getData = function(vars) {
1394        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1395            Strophe.debug("Retrieving JSONStore data");
1396            var xhr = this._newXHR();
1397            var getdata = "get=" + vars.join(",");
1398            try {
1399                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1400            } catch (e) {
1401                Strophe.error("JSONStore open failed.");
1402                return false;
1403            }
1404            xhr.setRequestHeader('Content-type',
1405            'application/x-www-form-urlencoded');
1406            xhr.setRequestHeader('Content-length', getdata.length);
1407            xhr.send(getdata);
1408            if (xhr.readyState == 4 && xhr.status == 200) {
1409                try {
1410                    var dataObj = JSON.parse(xhr.responseText);
1411                    return this.emptyFix(dataObj);
1412                } catch(e) {
1413                    Strophe.error("Could not parse JSONStore response" +
1414                    xhr.responseText);
1415                    return false;
1416                }
1417            } else {
1418                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1419                return false;
1420            }
1421        }
1422    }
1423    /** Function emptyFix
1424     *    Fix for bugs in external JSON implementations such as
1425     *    http://bugs.php.net/bug.php?id=41504.
1426     *    A.K.A. Don't use PHP, people.
1427     */
1428    this.emptyFix = function(obj) {
1429        if (typeof(obj) == "object") {
1430            for (var i in obj) {
1431                if (i == '_empty_') {
1432                    obj[""] = this.emptyFix(obj['_empty_']);
1433                    delete obj['_empty_'];
1434                } else {
1435                    obj[i] = this.emptyFix(obj[i]);
1436                }
1437            }
1438        }
1439        return obj
1440    }
1441    /** Function delData
1442     *    Deletes data from JSONStore
1443     *
1444     *  Parameters:
1445     *    (Array) vars  = Variables to delete from JSON store
1446     *
1447     *  Returns:
1448     *    Status of delete attempt.
1449     */
1450    this.delData = function(vars) {
1451        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1452            Strophe.debug("Retrieving JSONStore data");
1453            var xhr = this._newXHR();
1454            var deldata = "del=" + vars.join(",");
1455            try {
1456                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1457            } catch (e) {
1458                Strophe.error("JSONStore open failed.");
1459                return false;
1460            }
1461            xhr.setRequestHeader('Content-type',
1462            'application/x-www-form-urlencoded');
1463            xhr.setRequestHeader('Content-length', deldata.length);
1464            xhr.send(deldata);
1465            if (xhr.readyState == 4 && xhr.status == 200) {
1466                try {
1467                    var dataObj = JSON.parse(xhr.responseText);
1468                    return dataObj;
1469                } catch(e) {
1470                    Strophe.error("Could not parse JSONStore response");
1471                    return false;
1472                }
1473            } else {
1474                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1475                return false;
1476            }
1477        }
1478    }
1479    /** Function setData
1480     *    Stores data in JSONStore, overwriting values if they exist
1481     *
1482     *  Parameters:
1483     *    (Object) vars : Object containing named vars to store ({name: value,
1484     *    othername: othervalue})
1485     *
1486     *  Returns:
1487     *    Status of storage attempt
1488     */
1489    this.setData = function(vars) {
1490        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1491            Strophe.debug("Storing JSONStore data");
1492            var senddata = "set=" + JSON.stringify(vars);
1493            var xhr = this._newXHR();
1494            try {
1495                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1496            } catch (e) {
1497                Strophe.error("JSONStore open failed.");
1498                return false;
1499            }
1500            xhr.setRequestHeader('Content-type',
1501            'application/x-www-form-urlencoded');
1502            xhr.setRequestHeader('Content-length', senddata.length);
1503            xhr.send(senddata);
1504            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
1505            "OK") {
1506                return true;
1507            } else {
1508                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1509                return false;
1510            }
1511        }
1512    }
1513    var testData = true;
1514    if (this.setData({testData:testData})) {
1515        var testResult = this.getData(['testData']);
1516        if (testResult && testResult['testData'] == true) {
1517            this.store_working = true;
1518        }
1519    }
1520}
1521/** Constants: Node types
1522 *
1523 * Implementations of constants that IE doesn't have, but we need.
1524 */
1525if (document.ELEMENT_NODE == null) {
1526    document.ELEMENT_NODE = 1;
1527    document.ATTRIBUTE_NODE = 2;
1528    document.TEXT_NODE = 3;
1529    document.CDATA_SECTION_NODE = 4;
1530    document.ENTITY_REFERENCE_NODE = 5;
1531    document.ENTITY_NODE = 6;
1532    document.PROCESSING_INSTRUCTION_NODE = 7;
1533    document.COMMENT_NODE = 8;
1534    document.DOCUMENT_NODE = 9;
1535    document.DOCUMENT_TYPE_NODE = 10;
1536    document.DOCUMENT_FRAGMENT_NODE = 11;
1537    document.NOTATION_NODE = 12;
1538}
1539
1540/** Function: importNode
1541 *
1542 *  document.importNode implementation for IE, which doesn't have importNode
1543 *
1544 *  Parameters:
1545 *    (Object) node - dom object
1546 *    (Boolean) allChildren - import node's children too
1547 */
1548if (!document.importNode) {
1549    document.importNode = function(node, allChildren) {
1550        switch (node.nodeType) {
1551            case document.ELEMENT_NODE:
1552                var newNode = document.createElement(node.nodeName);
1553                if (node.attributes && node.attributes.length > 0) {
1554                    for(var i = 0; i < node.attributes.length; i++) {
1555                        newNode.setAttribute(node.attributes[i].nodeName,
1556                        node.getAttribute(node.attributes[i].nodeName));
1557                    }
1558                }
1559                if (allChildren && node.childNodes &&
1560                node.childNodes.length > 0) {
1561                    for (var i = 0; i < node.childNodes.length; i++) {
1562                        newNode.appendChild(document.importNode(
1563                        node.childNodes[i], allChildren));
1564                    }
1565                }
1566                return newNode;
1567                break;
1568            case document.TEXT_NODE:
1569            case document.CDATA_SECTION_NODE:
1570            case document.COMMENT_NODE:
1571                return document.createTextNode(node.nodeValue);
1572                break;
1573        }
1574    };
1575}
1576
1577/**
1578 *
1579 * Bootstrap self into window.onload and window.onunload
1580 */
1581
1582/*
1583var oldonload = window.onload;
1584window.onload = function()
1585{
1586    if(oldonload)
1587        {
1588        oldonload();
1589    }
1590   
1591        TrophyIM.load();
1592};
1593*/
1594
1595var oldonunload = window.onunload;
1596window.onunload = function()
1597{
1598    if(oldonunload)
1599        {
1600        oldonunload();
1601    }
1602   
1603        TrophyIM.storeData();
1604}
Note: See TracBrowser for help on using the repository browser.