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

Revision 2511, 45.2 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Implementado o status de mensagem e a busca da foto no ldap.

  • 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            contact                     = barejid.toLowerCase();
618                contact                 = contact.substring(0, contact.indexOf('@'));
619           
620            if( TrophyIM.rosterObj.roster[barejid] )
621            {
622                    if( TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'] )
623                    {
624                        contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact']['name'];
625                    }
626            }
627
628            var message =
629            {
630                contact : "<font style='font-weight:bold; color:black;'>" + contact + "</font>",
631                msg             : Strophe.getText(elems[0])     
632            };
633
634            TrophyIM.makeChat(from); //Make sure we have a chat window
635            TrophyIM.addMessage(message, jid_lower);
636        }
637       
638        return true;
639    },
640   
641    /** Function: makeChat
642     *
643     *  Make sure chat window to given fulljid exists, switching chat context to
644     *  given resource
645     */
646     
647    makeChat : function(fulljid)
648    {
649        var barejid             = Strophe.getBareJidFromJid(fulljid);
650        var titleWindow = "";
651       
652        var paramsChatBox =
653        {
654                        'idChatBox'     : barejid + "__chatBox",
655                        'jidTo'                 : barejid,
656                                'path_jabberit' : path_jabberit
657        };
658
659        titleWindow = barejid.toLowerCase();
660                titleWindow = titleWindow.substring(0, titleWindow.indexOf('@'));
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
670        var winChatBox =
671        {
672                         id_window              : "window_chat_area_" + barejid,
673                         width                  : 387,
674                         height                 : 365,
675                         top                    : 100,
676                         left                   : 400,
677                         draggable              : true,
678                         visible                : "display",
679                         resizable              : true,
680                         zindex                 : loadIM.getZIndex(),
681                         title                  : titleWindow,
682                         closeAction    : "hidden",
683                         content                : loadIM.parse("chat_box","chatBox.xsl", paramsChatBox)
684        }
685       
686        _winBuild(winChatBox);
687
688        // Photo User;
689                loadIM.getPhotoUser(barejid);
690               
691                loadIM.configEvents( document.getElementById( barejid + '__sendBox'),
692                        'onkeyup', function(e)
693                        {
694                                if( e.keyCode == 13 )
695                                {
696                                        TrophyIM.sendMessage( barejid );
697                                        document.getElementById( barejid + '__sendBox').value = '';
698                                        return false;
699                                }
700                        }
701                );
702    },
703
704        /** Function addContacts
705         *
706         *  Parameters:
707         *              (string) jidFrom         
708         *      (string) jidTo
709         *              (string) name
710         *              (string) group   
711         */
712       
713        addContact : function( jidFrom, jidTo, name, group )
714        {
715                // Set Presence
716        var newPresence = $pres({from: jidFrom, to: jidTo, type: 'subscribe'}).tree();
717                       
718                TrophyIM.connection.send(newPresence);
719       
720        // Add Contact
721        var _id = TrophyIM.connection.getUniqueId('add');
722                var newContact = $iq({type: 'set', id: _id });
723                        newContact = newContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
724                        newContact = newContact.c('item').attrs({jid: jidTo, name:name });
725                        newContact = newContact.c('group').t(group).tree();
726
727                TrophyIM.connection.send(newContact);
728        },
729
730    /** Function: addMessage
731     *
732     *  Parameters:
733     *    (string) msg - the message to add
734     *    (string) jid - the jid of chat box to add the message to.
735     */
736       
737    addMessage : function(msg, jid)
738    {
739        var chatBox             = document.getElementById(jid + "__chatBox");
740        var messageDiv  = document.createElement("div");
741       
742                messageDiv.style.margin = "3px 0px 3px 3px";
743        messageDiv.innerHTML    = msg.contact + " : " + msg.msg ;
744               
745        chatBox.appendChild(messageDiv);
746        chatBox.scrollTop = chatBox.scrollHeight;
747    },
748       
749    /** Function: removeContact
750     *
751     *  Parameters:
752     *          (string) jidTo
753     */
754   
755    removeContact : function(jidTo, indexTo)
756    {
757        var divItenContact       = null;
758        var spanShow             = null;
759       
760        if( ( divItenContact = document.getElementById('itenContact_' + jidTo + '_' + indexTo )))
761        {       
762                spanShow = document.getElementById('span_show_itenContact_' + jidTo + '_' + indexTo )
763               
764                spanShow.parentNode.removeChild(spanShow);
765               
766                loadIM.removeGroup( divItenContact.parentNode );
767               
768                divItenContact.parentNode.removeChild(divItenContact);
769               
770                // Remove Contact
771                        var _id = TrophyIM.connection.getUniqueId('del');       
772                var delContact  = $iq({type: 'set', id: _id})
773                        delContact      = delContact.c('query').attrs({xmlns : 'jabber:iq:roster'});
774                        delContact      = delContact.c('item').attrs({jid: jidTo, subscription:'remove'}).tree();
775               
776                TrophyIM.connection.send(delContact);
777        }
778    },
779   
780    /** Function: renderRoster
781     *
782     *  Renders roster, looking only for jids flagged by setPresence as having
783     *  changed.
784     */
785   
786        renderRoster : function()
787        {
788                var roster_div = document.getElementById('JabberIMRoster');
789               
790                if( roster_div )
791                {
792                        var users = new Array();
793                       
794                        for( var user in TrophyIM.rosterObj.roster )
795                        {
796                                users[users.length] = TrophyIM.rosterObj.roster[user].contact.jid;
797                        }
798
799                        users.sort();
800                       
801                        var groups              = new Array();
802                        var flagGeral   = false;
803                       
804                        for (var group in TrophyIM.rosterObj.groups)
805                        {
806                                if( group )
807                                        groups[groups.length] = group;
808                               
809                                if( group == "Geral" )
810                                        flagGeral = true;
811            }
812           
813                        if( !flagGeral && users.length > 0 )
814                                groups[groups.length] = "Geral";
815                               
816                        groups.sort();
817                       
818                        for ( var i = 0; i < groups.length; i++ )
819                        {
820                                TrophyIM.renderGroups( groups[i] , roster_div );       
821                        }
822                       
823                        TrophyIM.renderItensGroup( users, roster_div );
824                }
825                       
826                setTimeout("TrophyIM.renderRoster()", 1000 );           
827        },
828       
829    /** Function: renderGroups
830     *
831     *
832     */
833       
834        renderGroups: function( nameGroup, element )
835        {
836                var _addGroup = function()
837                {
838                        var _nameGroup  = nameGroup;
839                        var _element    = element;
840
841                        var paramsGroup =
842                        {
843                                'nameGroup'     : _nameGroup,
844                                'path_jabberit' : path_jabberit
845                        }
846                       
847                        _element.innerHTML += loadIM.parse("group","groups.xsl", paramsGroup);
848                }
849
850                if( !element.hasChildNodes() )
851                {
852                        _addGroup();
853                }
854                else
855                {
856                        var _NodeChild  = element.firstChild;
857                        var flagAdd             = false;
858                       
859                        while( _NodeChild )
860                        {
861                                if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
862                                {
863                                        if( _NodeChild.childNodes[0].childNodes[0].nodeValue === nameGroup )
864                                        {
865                                                flagAdd = true;
866                                        }
867                                }
868                               
869                                _NodeChild = _NodeChild.nextSibling;
870                        }
871
872                        if( !flagAdd )
873                        {
874                                _addGroup();
875                        }
876                }
877        },
878
879    /** Function: renderItensGroup
880     *
881     *
882     */
883
884        renderItensGroup : function( users, element )
885        {
886                var addItem = function()
887                {
888                        if( arguments.length > 0 )
889                        {
890                                var objContact  = arguments[0];
891                                var group               = arguments[1];
892                                var element             = arguments[2];
893                                var index               = arguments[3];
894
895                                var itensJid    = document.getElementById( 'itenContact_' + objContact.contact.jid + '_' + index );
896                               
897                                if( itensJid == null )
898                                {
899                                        // Name
900                                        var nameContact = "";                                   
901                                       
902                                        if ( objContact.contact.name )
903                                                nameContact = objContact.contact.name;
904                                        else
905                                        {
906                                                nameContact = objContact.contact.jid;
907                                                nameContact = nameContact.substring(0, nameContact.indexOf('@'));
908                                        }
909                                       
910                                        // Presence e Status
911                                        var presence            = "unavailable";
912                                        var status                      = "";
913                                        var statusDisplay       = "none";
914                                       
915                                        if (objContact.presence)
916                                        {
917                                                for (var resource in objContact.presence)
918                                                {
919                                                        if( objContact.presence[resource].show != 'invisible' )
920                                                                presence = objContact.presence[resource].show;
921
922                                                        if( objContact.presence[resource].status )
923                                                        {
924                                                                status                  = " ( " + objContact.presence[resource].status + " ) ";
925                                                                statusDisplay   = "block";
926                                                        }
927                                                }
928                                        }
929                                       
930                                        var paramsContact =
931                                        {
932                                                'nameContact'   : nameContact,
933                                                'jid'                   : objContact.contact.jid,       
934                                                'id'                    : 'itenContact_' + objContact.contact.jid + '_' + index ,
935                                                'index'                 : index,
936                                                'path_jabberit' : path_jabberit,
937                                                'presence'              : presence,
938                                                'status'                : status,
939                                                'statusDisplay' : statusDisplay,
940                                                'subscription'  : objContact.contact.subscription
941                                        }
942                                       
943                                        if( group != "")
944                                        {
945                                                var _NodeChild          = element.firstChild;
946                                               
947                                                while( _NodeChild )
948                                                {
949                                                        if( _NodeChild.childNodes[0].nodeName.toLowerCase() === "span" )
950                                                        {
951                                                                if( _NodeChild.childNodes[0].childNodes[0].nodeValue === group )
952                                                                {
953                                                                        _NodeChild.innerHTML += loadIM.parse("itens_group", "itensGroup.xsl", paramsContact);
954                                                                }
955                                                        }
956
957                                                        _NodeChild = _NodeChild.nextSibling;
958                                                }
959                                        }       
960                                }
961                                else
962                                {
963                                        // Presence e Status
964                                        var presence            = "unavailable";
965                                        var status                      = "";
966                                        var statusDisplay       = "none";
967                                       
968                                        if (objContact.presence)
969                                        {
970                                                for ( var resource in objContact.presence )
971                                                {
972                                                        if( objContact.presence[resource].show != 'invisible' )
973                                                                presence = objContact.presence[resource].show;
974
975                                                        if( objContact.presence[resource].status )
976                                                        {
977                                                                status                  = " ( " + objContact.presence[resource].status + " ) ";
978                                                                statusDisplay   = "block";
979                                                        }
980                                                }       
981                                        }
982                                               
983                                        var is_open = itensJid.parentNode.childNodes[0].style.backgroundImage; 
984                                                is_open = is_open.indexOf("arrow_down.gif");
985                                       
986                                        with ( document.getElementById('span_show_' + 'itenContact_' + objContact.contact.jid + '_' + index ) )
987                                        {
988                                                if( is_open > 0 )
989                                                {
990                                                        style.display   = statusDisplay;
991                                                        innerHTML               = status;
992                                                }
993                                        }
994                                       
995                                        itensJid.style.background       = "url('"+path_jabberit+"templates/default/images/" + presence + ".gif')no-repeat center left";
996                                }
997                        }
998                }
999               
1000                for( var i = 0 ; i < users.length; i++ )
1001                {
1002                        if( TrophyIM.rosterObj.roster[users[i]].contact.jid != loadIM.getUserCurrent().jid )
1003                        {
1004                                if( TrophyIM.rosterObj.roster[users[i]].contact.groups )
1005                                {
1006                                        var groups = TrophyIM.rosterObj.roster[users[i]].contact.groups;
1007                                       
1008                                        if( groups.length > 0 )
1009                                        {
1010                                                for( var j = 0; j < groups.length; j++ )
1011                                                        addItem( TrophyIM.rosterObj.roster[users[i]], groups[j], element, j );
1012                                        }
1013                                        else
1014                                        {
1015                                                addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1016                                        }
1017                                }
1018                                else
1019                                {
1020                                        addItem( TrophyIM.rosterObj.roster[users[i]], "Geral", element, 0 );
1021                                }
1022                        }
1023                }       
1024        },
1025
1026    /** Function: rosterClick
1027     *
1028     *  Handles actions when a roster item is clicked
1029     */
1030   
1031        rosterClick : function(fulljid)
1032        {
1033        TrophyIM.makeChat(fulljid);
1034    },
1035
1036
1037        /** Function SetAutorization
1038         *
1039         */
1040
1041        setAutorization : function( jidTo, jidFrom, _typeSubscription )
1042        {
1043        var _id = TrophyIM.connection.getUniqueId();
1044       
1045        TrophyIM.connection.send($pres( ).attrs( {to: jidTo, from: jidFrom, type: _typeSubscription, id: _id}).tree());
1046        },
1047   
1048        /** Function: setPresence
1049     *
1050     */
1051
1052        setPresence : function( type )
1053        {
1054                if( type != 'status')
1055                {
1056                        TrophyIM.connection.send($pres( ).c('show').t(type).tree());
1057                }
1058                else
1059                {
1060                        var _show       = "available";
1061                        var _status     = "";
1062                       
1063                        if (( _status = prompt("Digite sua mensagem !") ))
1064                        {
1065                                for(var resource in TrophyIM.rosterObj.roster[loadIM.getUserCurrent().jid].presence )
1066                                {       
1067                                        if ( TROPHYIM_RESOURCE === ("/" + resource) )
1068                                                _show = TrophyIM.rosterObj.roster[loadIM.getUserCurrent().jid].presence[resource].show;
1069                                }
1070
1071                                var _presence = $pres( );
1072                                _presence.node.appendChild( Strophe.xmlElement( 'show' ) ).appendChild( Strophe.xmlTextNode( _show ) );
1073                                _presence.node.appendChild( Strophe.xmlElement( 'status' ) ).appendChild( Strophe.xmlTextNode( _status ) );
1074                               
1075                                TrophyIM.connection.send( _presence.tree() );
1076                        }
1077                }
1078        },
1079       
1080        /** Function: sendMessage
1081     *
1082     *  Send message from chat input to user
1083     */
1084     
1085    sendMessage : function()
1086    {
1087
1088        if( arguments.length > 0 )
1089        {
1090                var jidTo = arguments[0];
1091                var message_input = document.getElementById(jidTo + "__sendBox").value;
1092           
1093                if( ( message_input = message_input.replace(/^\s+|\s+$|^\n|\n$/g,"") ) != "" )
1094                {
1095                        // Send Message
1096                        TrophyIM.connection.send($msg({to: jidTo, from: TrophyIM.connection.jid, type: 'chat'}).c('body').t(message_input).tree());
1097                       
1098                        var message =
1099                        {
1100                                        contact : "<font style='font-weight:bold; color:red;'>" + "Eu" + "</font>",
1101                                        msg : message_input
1102                        }
1103                       
1104                        // Add Message in chatBox;
1105                        TrophyIM.addMessage( message, jidTo);
1106                                document.getElementById(jidTo + "__sendBox").value = "";
1107                                document.getElementById(jidTo + "__sendBox").focus();
1108                }
1109        }
1110    }
1111};
1112
1113/** Class: TrophyIMRoster
1114 *
1115 *
1116 *  This object stores the roster and presence info for the TrophyIMClient
1117 *
1118 *  roster[jid_lower]['contact']
1119 *  roster[jid_lower]['presence'][resource]
1120 */
1121function TrophyIMRoster()
1122{
1123    /** Constants: internal arrays
1124     *    (Object) roster - the actual roster/presence information
1125     *    (Object) groups - list of current groups in the roster
1126     *    (Array) changes - array of jids with presence changes
1127     */
1128    if (TrophyIM.JSONStore.store_working)
1129        {
1130        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1131        this.roster = (data['roster'] != null) ? data['roster'] : {};
1132        this.groups = (data['groups'] != null) ? data['groups'] : {};
1133    }
1134        else
1135        {
1136        this.roster = {};
1137        this.groups = {};
1138    }
1139    this.changes = new Array();
1140   
1141        if (TrophyIM.constants.stale_roster)
1142        {
1143        for (var jid in this.roster)
1144                {
1145                        this.changes[this.changes.length] = jid;
1146        }
1147    }
1148
1149        /** Function: addChange
1150         *
1151         *  Adds given jid to this.changes, keeping this.changes sorted and
1152         *  preventing duplicates.
1153         *
1154         *  Parameters
1155         *    (String) jid : jid to add to this.changes
1156         */
1157         
1158        this.addChange = function(jid)
1159        {
1160                for (var c = 0; c < this.changes.length; c++)
1161                {
1162                        if (this.changes[c] == jid)
1163                        {
1164                                return;
1165                        }
1166                }
1167               
1168                this.changes[this.changes.length] = jid;
1169               
1170                this.changes.sort();
1171        }
1172       
1173    /** Function: addContact
1174     *
1175     *  Adds given contact to roster
1176     *
1177     *  Parameters:
1178     *    (String) jid - bare jid
1179     *    (String) subscription - subscription attribute for contact
1180     *    (String) name - name attribute for contact
1181     *    (Array)  groups - array of groups contact is member of
1182     */
1183   
1184        this.addContact = function(jid, subscription, name, groups )
1185        {
1186                if( subscription !== "remove" )
1187        {
1188                var contact             = { jid:jid, subscription:subscription, name:name, groups:groups }
1189                var jid_lower   = jid.toLowerCase();
1190       
1191                        if ( this.roster[jid_lower] )
1192                        {
1193                    this.roster[jid_lower]['contact'] = contact;
1194                }
1195                        else
1196                        {
1197                    this.roster[jid_lower] = {contact:contact};
1198                }
1199       
1200                        groups = groups ? groups : [''];
1201               
1202                        for ( var g = 0; g < groups.length; g++ )
1203                        {
1204                                if ( !this.groups[groups[g]] )
1205                                {
1206                        this.groups[groups[g]] = {};
1207                    }
1208                   
1209                                this.groups[groups[g]][jid_lower] = jid_lower;
1210                }
1211        }
1212        else
1213        {
1214                this.removeContact(jid);
1215        }
1216    }
1217   
1218    /** Function: getContact
1219     *
1220     *  Returns contact entry for given jid
1221     *
1222     *  Parameter: (String) jid - jid to return
1223     */
1224     
1225    this.getContact = function(jid)
1226        {
1227        if (this.roster[jid.toLowerCase()])
1228                {
1229            return this.roster[jid.toLowerCase()]['contact'];
1230        }
1231    }
1232
1233   /** Function: getPresence
1234        *
1235        *  Returns best presence for given jid as Array(resource, priority, show,
1236        *  status)
1237        *
1238        *  Parameter: (String) fulljid - jid to return best presence for
1239        */
1240         
1241        this.getPresence = function(fulljid)
1242        {
1243                var jid = Strophe.getBareJidFromJid(fulljid);
1244                var current = null;
1245                   
1246                if (this.roster[jid.toLowerCase()] && this.roster[jid.toLowerCase()]['presence'])
1247                {
1248                        for (var resource in this.roster[jid.toLowerCase()]['presence'])
1249                        {
1250                                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1251                                if (current == null)
1252                                {
1253                                        current = presence
1254                                }
1255                                else
1256                                {
1257                                        if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1258                                        || presence['show'] == "available") || (current['show'] != "chat" ||
1259                                        current['show'] != "available")))
1260                                        {
1261                                                current = presence
1262                                        }
1263                                }
1264                        }
1265                }
1266                return current;
1267        }
1268
1269        /** Function: groupHasChanges
1270         *
1271         *  Returns true if current group has members in this.changes
1272         *
1273         *  Parameters:
1274         *    (String) group - name of group to check
1275         */
1276         
1277        this.groupHasChanges = function(group)
1278        {
1279                for (var c = 0; c < this.changes.length; c++)
1280                {
1281                        if (this.groups[group][this.changes[c]])
1282                        {
1283                                return true;
1284                        }
1285                }
1286                return false;
1287        }
1288       
1289        /** Function removeContact
1290         *
1291         * Parameters
1292         *       (String) jid           
1293         */
1294         
1295         this.removeContact = function(jid)
1296         {
1297                var groups = this.roster[ jid ].contact.groups;
1298               
1299                if( groups )
1300                {
1301                       
1302                        for ( var i = 0; i < groups.length; i++ )
1303                        {
1304                                delete this.groups[ groups[ i ] ][ jid ];
1305                        }
1306
1307                        for ( var i = 0; i < groups.length; i++ )
1308                        {
1309                                var contacts = 0;
1310                                for ( var contact in this.groups[ groups[ i ] ] )
1311                                        contacts++;
1312       
1313                                if ( ! contacts )
1314                                        delete this.groups[ groups[ i ] ];
1315                        }
1316                }
1317
1318                // Delete Object roster
1319                if( this.roster[jid] )
1320                        delete this.roster[jid];               
1321         }
1322         
1323    /** Function: setPresence
1324     *
1325     *  Sets presence
1326     *
1327     *  Parameters:
1328     *    (String) fulljid: full jid with presence
1329     *    (Integer) priority: priority attribute from presence
1330     *    (String) show: show attribute from presence
1331     *    (String) status: status attribute from presence
1332     */
1333   
1334        this.setPresence = function(fulljid, priority, show, status)
1335        {
1336                var barejid = Strophe.getBareJidFromJid(fulljid);
1337        var resource = Strophe.getResourceFromJid(fulljid);
1338        var jid_lower = barejid.toLowerCase();
1339       
1340                if( show != 'unavailable')
1341                {
1342            if (!this.roster[jid_lower])
1343                        {
1344                this.addContact(barejid, 'not-in-roster');
1345            }
1346            var presence =
1347                        {
1348                resource:resource, priority:priority, show:show, status:status
1349            }
1350           
1351                        if (!this.roster[jid_lower]['presence'])
1352                        {
1353                this.roster[jid_lower]['presence'] = {}
1354            }
1355            this.roster[jid_lower]['presence'][resource] = presence
1356        }
1357                else if (this.roster[jid_lower] && this.roster[jid_lower]['presence'] && this.roster[jid_lower]['presence'][resource])
1358                {
1359            delete this.roster[jid_lower]['presence'][resource];
1360        }
1361       
1362                this.addChange(jid_lower);
1363    }
1364
1365        /** Fuction: save
1366         *
1367         *  Saves roster data to JSON store
1368         */
1369       
1370        this.save = function()
1371        {
1372                if (TrophyIM.JSONStore.store_working)
1373                {
1374                        TrophyIM.JSONStore.setData({roster:this.roster,
1375                        groups:this.groups, active_chat:TrophyIM.activeChats['current'],
1376                        chat_history:TrophyIM.chatHistory});
1377                }
1378        }
1379
1380}
1381/** Class: TrophyIMJSONStore
1382 *
1383 *
1384 *  This object is the mechanism by which TrophyIM stores and retrieves its
1385 *  variables from the url provided by TROPHYIM_JSON_STORE
1386 *
1387 */
1388function TrophyIMJSONStore() {
1389    this.store_working = false;
1390    /** Function _newXHR
1391     *
1392     *  Set up new cross-browser xmlhttprequest object
1393     *
1394     *  Parameters:
1395     *    (function) handler = what to set onreadystatechange to
1396     */
1397     this._newXHR = function (handler) {
1398        var xhr = null;
1399        if (window.XMLHttpRequest) {
1400            xhr = new XMLHttpRequest();
1401            if (xhr.overrideMimeType) {
1402            xhr.overrideMimeType("text/xml");
1403            }
1404        } else if (window.ActiveXObject) {
1405            xhr = new ActiveXObject("Microsoft.XMLHTTP");
1406        }
1407        return xhr;
1408    }
1409    /** Function getData
1410     *  Gets data from JSONStore
1411     *
1412     *  Parameters:
1413     *    (Array) vars = Variables to get from JSON store
1414     *
1415     *  Returns:
1416     *    Object with variables indexed by names given in parameter 'vars'
1417     */
1418    this.getData = function(vars) {
1419        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1420            Strophe.debug("Retrieving JSONStore data");
1421            var xhr = this._newXHR();
1422            var getdata = "get=" + vars.join(",");
1423            try {
1424                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1425            } catch (e) {
1426                Strophe.error("JSONStore open failed.");
1427                return false;
1428            }
1429            xhr.setRequestHeader('Content-type',
1430            'application/x-www-form-urlencoded');
1431            xhr.setRequestHeader('Content-length', getdata.length);
1432            xhr.send(getdata);
1433            if (xhr.readyState == 4 && xhr.status == 200) {
1434                try {
1435                    var dataObj = JSON.parse(xhr.responseText);
1436                    return this.emptyFix(dataObj);
1437                } catch(e) {
1438                    Strophe.error("Could not parse JSONStore response" +
1439                    xhr.responseText);
1440                    return false;
1441                }
1442            } else {
1443                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1444                return false;
1445            }
1446        }
1447    }
1448    /** Function emptyFix
1449     *    Fix for bugs in external JSON implementations such as
1450     *    http://bugs.php.net/bug.php?id=41504.
1451     *    A.K.A. Don't use PHP, people.
1452     */
1453    this.emptyFix = function(obj) {
1454        if (typeof(obj) == "object") {
1455            for (var i in obj) {
1456                if (i == '_empty_') {
1457                    obj[""] = this.emptyFix(obj['_empty_']);
1458                    delete obj['_empty_'];
1459                } else {
1460                    obj[i] = this.emptyFix(obj[i]);
1461                }
1462            }
1463        }
1464        return obj
1465    }
1466    /** Function delData
1467     *    Deletes data from JSONStore
1468     *
1469     *  Parameters:
1470     *    (Array) vars  = Variables to delete from JSON store
1471     *
1472     *  Returns:
1473     *    Status of delete attempt.
1474     */
1475    this.delData = function(vars) {
1476        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1477            Strophe.debug("Retrieving JSONStore data");
1478            var xhr = this._newXHR();
1479            var deldata = "del=" + vars.join(",");
1480            try {
1481                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1482            } catch (e) {
1483                Strophe.error("JSONStore open failed.");
1484                return false;
1485            }
1486            xhr.setRequestHeader('Content-type',
1487            'application/x-www-form-urlencoded');
1488            xhr.setRequestHeader('Content-length', deldata.length);
1489            xhr.send(deldata);
1490            if (xhr.readyState == 4 && xhr.status == 200) {
1491                try {
1492                    var dataObj = JSON.parse(xhr.responseText);
1493                    return dataObj;
1494                } catch(e) {
1495                    Strophe.error("Could not parse JSONStore response");
1496                    return false;
1497                }
1498            } else {
1499                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1500                return false;
1501            }
1502        }
1503    }
1504    /** Function setData
1505     *    Stores data in JSONStore, overwriting values if they exist
1506     *
1507     *  Parameters:
1508     *    (Object) vars : Object containing named vars to store ({name: value,
1509     *    othername: othervalue})
1510     *
1511     *  Returns:
1512     *    Status of storage attempt
1513     */
1514    this.setData = function(vars) {
1515        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1516            Strophe.debug("Storing JSONStore data");
1517            var senddata = "set=" + JSON.stringify(vars);
1518            var xhr = this._newXHR();
1519            try {
1520                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1521            } catch (e) {
1522                Strophe.error("JSONStore open failed.");
1523                return false;
1524            }
1525            xhr.setRequestHeader('Content-type',
1526            'application/x-www-form-urlencoded');
1527            xhr.setRequestHeader('Content-length', senddata.length);
1528            xhr.send(senddata);
1529            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
1530            "OK") {
1531                return true;
1532            } else {
1533                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1534                return false;
1535            }
1536        }
1537    }
1538    var testData = true;
1539    if (this.setData({testData:testData})) {
1540        var testResult = this.getData(['testData']);
1541        if (testResult && testResult['testData'] == true) {
1542            this.store_working = true;
1543        }
1544    }
1545}
1546/** Constants: Node types
1547 *
1548 * Implementations of constants that IE doesn't have, but we need.
1549 */
1550if (document.ELEMENT_NODE == null) {
1551    document.ELEMENT_NODE = 1;
1552    document.ATTRIBUTE_NODE = 2;
1553    document.TEXT_NODE = 3;
1554    document.CDATA_SECTION_NODE = 4;
1555    document.ENTITY_REFERENCE_NODE = 5;
1556    document.ENTITY_NODE = 6;
1557    document.PROCESSING_INSTRUCTION_NODE = 7;
1558    document.COMMENT_NODE = 8;
1559    document.DOCUMENT_NODE = 9;
1560    document.DOCUMENT_TYPE_NODE = 10;
1561    document.DOCUMENT_FRAGMENT_NODE = 11;
1562    document.NOTATION_NODE = 12;
1563}
1564
1565/** Function: importNode
1566 *
1567 *  document.importNode implementation for IE, which doesn't have importNode
1568 *
1569 *  Parameters:
1570 *    (Object) node - dom object
1571 *    (Boolean) allChildren - import node's children too
1572 */
1573if (!document.importNode) {
1574    document.importNode = function(node, allChildren) {
1575        switch (node.nodeType) {
1576            case document.ELEMENT_NODE:
1577                var newNode = document.createElement(node.nodeName);
1578                if (node.attributes && node.attributes.length > 0) {
1579                    for(var i = 0; i < node.attributes.length; i++) {
1580                        newNode.setAttribute(node.attributes[i].nodeName,
1581                        node.getAttribute(node.attributes[i].nodeName));
1582                    }
1583                }
1584                if (allChildren && node.childNodes &&
1585                node.childNodes.length > 0) {
1586                    for (var i = 0; i < node.childNodes.length; i++) {
1587                        newNode.appendChild(document.importNode(
1588                        node.childNodes[i], allChildren));
1589                    }
1590                }
1591                return newNode;
1592                break;
1593            case document.TEXT_NODE:
1594            case document.CDATA_SECTION_NODE:
1595            case document.COMMENT_NODE:
1596                return document.createTextNode(node.nodeValue);
1597                break;
1598        }
1599    };
1600}
1601
1602/**
1603 *
1604 * Bootstrap self into window.onload and window.onunload
1605 */
1606
1607/*
1608var oldonload = window.onload;
1609window.onload = function()
1610{
1611    if(oldonload)
1612        {
1613        oldonload();
1614    }
1615   
1616        TrophyIM.load();
1617};
1618*/
1619
1620var oldonunload = window.onunload;
1621window.onunload = function()
1622{
1623    if(oldonunload)
1624        {
1625        oldonunload();
1626    }
1627   
1628        TrophyIM.storeData();
1629}
Note: See TracBrowser for help on using the repository browser.