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

Revision 2577, 47.0 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Alterado a parte de autorizacao, informando se o usuario esta permitido ou nao na lista.

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