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

Revision 2607, 48.5 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Codificacao da senha para nao passar em texto puro

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