source: sandbox/jabberit_messenger/trophy/js/trophyim.js @ 2271

Revision 2271, 57.2 KB checked in by alexandrecorreia, 14 years ago (diff)

Ticket #986 - Reimplementar interface mais leve para o IM, sem a necessidades de plugins adicionais.

  • 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/*TODO dump / very loose roadmap
8--0.4
9add chats to json store
10Mouseover status messages in roster
11HTML in messages (xslt?)
12Select presence status/message
13Optional user-specified resource
14Loglevel select on login instead of check box
15vcard support http://xmpp.org/extensions/xep-0153.html
16Notifications of closed chats
17Notifications of typing
18--0.5
19roster management
20figure out how we want to handle presence from our own jid (and transports)
21roster sorting by presence / offline roster capablility
22auto-subscribe vs prompted subscribe based on config option
23make sure makeChat() et al. can handle empty resources
24    (offline chat capabilities)
25--1.0 (or whenever someone submits better .css)
26layout overhaul
27code cleanup (like checking for excessive function lengths)
28roster versioning http://xmpp.org/extensions/attic/xep-0237-0.1.html
29make sure onload bootstrapping actually preserves existing onloads
30*/
31var TROPHYIM_BOSH_SERVICE = '/proxy/xmpp-httpbind';  //Change to suit
32var TROPHYIM_LOG_LINES = 200;
33var TROPHYIM_LOGLEVEL = 0; //0=debug, 1=info, 2=warn, 3=error, 4=fatal
34var TROPHYIM_VERSION = "0.3";
35//Uncomment to make session reattachment work
36//var TROPHYIM_JSON_STORE = "json_store.php";
37
38/** File: trophyimclient.js
39 *  A JavaScript front-end for strophe.js
40 *
41 *  This is a JavaScript library that runs on top of strophe.js.  All that
42 *  is required is that your page have a <div> element with an id of
43 *  'trophyimclient', and that your page does not explicitly set an onload
44 *  event in its <body> tag.  In that case you need to append TrophyIM.load()
45 *  to it.
46 *
47 *  The style of the client can be conrolled via trophyim.css, which is
48 *  auto-included by the client.
49 */
50
51/** Object: HTMLSnippets
52 *
53 *  This is the repository for all the html snippets that TrophyIM uses
54 *
55 */
56HTMLSnippets = {
57
58                chatArea        : loadIM.HTMLSnippets.chatArea( ),
59               
60        chatBox         : loadIM.HTMLSnippets.chatBox( ),
61
62        chatTab         : loadIM.HTMLSnippets.chatTab( ),
63               
64                //loginPage     : loadIM.HTMLSnippets.loginPage( ),
65   
66        loggingDiv      : loadIM.HTMLSnippets.loggingDiv( ),
67   
68        rosterDiv       : loadIM.HTMLSnippets.rosterDiv( ),
69   
70        rosterGroup     : loadIM.HTMLSnippets.rosterGroup( ),
71       
72        rosterItem      : loadIM.HTMLSnippets.rosterItem( ),
73   
74        statusDiv       : loadIM.HTMLSnippets.statusDiv( ),
75};
76
77/** Object: DOMObjects
78 *  This class contains builders for all the DOM objects needed by TrophyIM
79 */
80DOMObjects = {
81    /** Function: xmlParse
82     *  Cross-browser alternative to using innerHTML
83     *  Parses given string, returns valid DOM HTML object
84     *
85     *  Parameters:
86     *    (String) xml - the xml string to parse
87     */
88    xmlParse : function(xmlString) {
89        var xmlObj = this.xmlRender(xmlString);
90        if(xmlObj) {
91            try { //Firefox, Gecko, etc
92                if (this.processor == undefined) {
93                    this.processor = new XSLTProcessor();
94                    this.processor.importStylesheet(this.xmlRender(
95                    '<xsl:stylesheet version="1.0"\
96                    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
97                    <xsl:output method="html" indent="yes"/><xsl:template\
98                    match="@*|node()"><xsl:copy><xsl:copy-of\
99                    select="@*|node()"/></xsl:copy></xsl:template>\
100                    </xsl:stylesheet>'));
101                }
102                var htmlObj =
103                this.processor.transformToDocument(xmlObj).documentElement;
104                //Safari has a quirk where it wraps dom elements in <html><body>
105                if (htmlObj.tagName.toLowerCase() == 'html') {
106                    htmlObj = htmlObj.firstChild.firstChild;
107                }
108                return document.importNode(htmlObj, true);
109            } catch(e) {
110                try { //IE is so very very special
111                    var htmlObj = document.importNode(xmlObj.documentElement, true);
112                    if (htmlObj.tagName.toLowerCase() == "div") {
113                        var div_wrapper = document.createElement('div');
114                        div_wrapper.appendChild(htmlObj);
115                        if(div_wrapper.innerHTML) {
116                            div_wrapper.innerHTML = div_wrapper.innerHTML;
117                        }
118                        htmlObj = div_wrapper.firstChild;
119                    }
120                    return htmlObj;
121                } catch(e) {
122                    alert(
123                    "TrophyIM Error: Cannot add html to page" + e.message);
124                }
125            }
126        }
127    },
128    /** Function: xmlRender
129     *  Uses browser-specific methods to turn given string into xml object
130     *
131     *  Parameters:
132     *    (String) xml - the xml string to parse
133     */
134    xmlRender : function(xmlString) {
135        try {//IE
136            var renderObj = new ActiveXObject("Microsoft.XMLDOM");
137            renderObj.async="false";
138            if(xmlString) {
139                renderObj.loadXML(xmlString);
140            }
141        } catch (e) {
142            try { //Firefox, Gecko, etc
143                if (this.parser == undefined) {
144                    this.parser = new DOMParser();
145                }
146                var renderObj = this.parser.parseFromString(xmlString,
147                "application/xml");
148            } catch(e) {
149                alert("TrophyIM Error: Cannot create new html for page");
150            }
151        }
152
153        return renderObj;
154    },
155    /** Function: getHTML
156     *  Returns named HTML snippet as DOM object
157     *
158     *  Parameters:
159     *    (String) name - name of HTML snippet to retrieve (see HTMLSnippets
160     *    object)
161     */
162    getHTML : function(page) {
163        //alert("Page : \n" + page);
164        return this.xmlParse(HTMLSnippets[page]);
165    },
166    /** Function: getScript
167     *  Returns script object with src to given script
168     *
169     *  Parameters:
170     *    (String) script - name of script to put in src attribute of script
171     *    element
172     */
173    getScript : function(script) {
174        var newscript = document.createElement('script');
175        newscript.setAttribute('src', script);
176        newscript.setAttribute('type', 'text/javascript');
177        return newscript;
178    }
179};
180
181/** Object: TrophyIM
182 *
183 *  This is the actual TrophyIM application.  It searches for the
184 *  'trophyimclient' element and inserts itself into that.
185 */
186TrophyIM = {
187    /** Constants:
188     *
189     *    (Boolean) stale_roster - roster is stale and needs to be rewritten.
190     */
191    constants : {stale_roster: false},
192    /** Object: chatHistory
193     *
194     *  Stores chat history (last 10 message) and current presence of active
195     *  chat tabs.  Indexed by jid.
196     */
197    chatHistory : {},
198    /** Object: activeChats
199     *
200     *  This object stores the currently active chats.
201     */
202    activeChats : {current: null, divs: {}},
203    /** Function: setCookie
204     *
205     *  Sets cookie name/value pair.  Date and path are auto-selected.
206     *
207     *  Parameters:
208     *    (String) name - the name of the cookie variable
209     *    (String) value - the value of the cookie variable
210     */
211    setCookie : function(name, value) {
212        var expire = new Date();
213        expire.setDate(expire.getDate() + 365);
214        document.cookie = name + "=" + value + "; expires=" + expire.toGMTString();
215    },
216    /** Function: delCookie
217     *
218     *  Deletes cookie
219     *
220     *  Parameters:
221     *    (String) name) - the name of the cookie to delete
222     */
223    delCookie : function(name) {
224        var expire = new Date();
225        expire.setDate(expire.getDate() - 365);
226        document.cookie = name + "= ; expires=" + expire.toGMTString();
227        delete TrophyIM.cookies[name];
228    },
229    /** Function: getCookies
230     *
231     *  Retrieves all trophyim cookies into an indexed object.  Inteneded to be
232     *  called once, at which time the app refers to the returned object instead
233     *  of re-parsing the cookie string every time.
234     *
235     *  Each cookie is also re-applied so as to refresh the expiry date.
236     */
237    getCookies : function() {
238        var cObj = {};
239        var cookies = document.cookie.split(';');
240        for (var c in cookies) {
241            while (cookies[c].charAt(0)==' ') {
242                cookies[c] = cookies[c].substring(1,cookies[c].length);
243            }
244            if (cookies[c].substr(0, 8) == "trophyim") {
245                var nvpair = cookies[c].split("=", 2);
246                cObj[nvpair[0]] = nvpair[1];
247                TrophyIM.setCookie(nvpair[0], nvpair[1]);
248            }
249        }
250        return cObj;
251    },
252    /** Function: load
253     *
254     *  This function searches for the trophyimclient div and loads the client
255     *  into it.
256     */
257    load : function()
258        {
259                TrophyIM.cookies        = TrophyIM.getCookies();
260
261                TrophyIM.client_div = document.getElementById('trophyimclient');
262
263        //Load other .js scripts needed
264        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/strophe.js'));
265        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/md5.js'));
266        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/sha1.js'));
267        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/b64.js'));
268        document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('js/json2.js')); //Keep this script last
269
270                //Wait a second to give scripts time to load
271                setTimeout("TrophyIM.showLogin()", 500);
272
273            /*TrophyIM.cookies = TrophyIM.getCookies();
274        var client_div = document.getElementById('trophyimclient');
275        if (client_div)
276        {
277            TrophyIM.client_div = client_div;
278
279            //load .css
280            //document.getElementsByTagName('head')[0].appendChild(DOMObjects.getHTML('cssLink'));
281            //DOMObjects.getHTML('cssLink');
282           
283            //Load other .js scripts needed
284            document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/strophe.js'));
285            document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/md5.js'));
286            document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/sha1.js'));
287            document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('strophejs/b64.js'));
288            document.getElementsByTagName('head')[0].appendChild(DOMObjects.getScript('js/json2.js')); //Keep this script last
289           
290            //Wait a second to give scripts time to load
291            setTimeout("TrophyIM.showLogin()", 500);
292        } else {
293            alert("Cannot load TrophyIM client.\nClient div not found.");
294        }*/
295    },
296    /** Function: storeData
297     *
298     *  Store all our data in the JSONStore, if it is active
299     */
300    storeData : function() {
301        if (TrophyIM.connection && TrophyIM.connection.connected) {
302            TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
303            TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
304            TrophyIM.rosterObj.save();
305        }
306    },
307    /**  Function: showlogin
308     *
309     *   This function clears out the IM box and either redisplays the login
310     *   page, or re-attaches to Strophe, preserving the logging div if it
311     *   exists, or creating a new one of we are re-attaching.
312     */
313    showLogin : function() {
314        //JSON is the last script to load, so we wait on it
315        //Added Strophe check too because of bug where it's sometimes missing
316        if (typeof(JSON) != undefined && typeof(Strophe) != undefined)
317        {
318                TrophyIM.JSONStore = new TrophyIMJSONStore();
319               
320            if ( TrophyIM.JSONStore.store_working && TrophyIM.cookies['trophyim_bosh_xid'] )
321            {
322                var xids = TrophyIM.cookies['trophyim_bosh_xid'].split("|");
323                TrophyIM.delCookie('trophyim_bosh_xid');
324                TrophyIM.constants.stale_roster = true;
325                if (TrophyIM.cookies['trophyimloglevel'])
326                {
327                    TrophyIM.client_div.appendChild(DOMObjects.getHTML('loggingDiv'));
328                    TrophyIM.logging_div = document.getElementById('trophyimlog');
329                }
330                TrophyIM.connection = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
331                TrophyIM.connection.rawInput = TrophyIM.rawInput;
332                TrophyIM.connection.rawOutput = TrophyIM.rawOutput;
333                Strophe.log = TrophyIM.log;
334                Strophe.info('Attempting Strophe attach.');
335                TrophyIM.connection.attach(xids[0], xids[1], xids[2], TrophyIM.onConnect);
336                TrophyIM.onConnect(Strophe.Status.CONNECTED);
337            }
338            else
339            {
340                var logging_div = TrophyIM.clearClient();
341                loadIM.HTMLSnippets.loginPage();
342            }
343        }
344        else
345        {
346                setTimeout("TrophyIM.showLogin()", 500);
347        }
348    },
349    /** Function: log
350     *
351     *  This function logs the given message in the trophyimlog div
352     *
353     *  Parameter: (String) msg - the message to log
354     */
355   
356    log : function(level, msg)
357    {
358        if (TrophyIM.logging_div && level >= TROPHYIM_LOGLEVEL) {
359            while(TrophyIM.logging_div.childNodes.length > TROPHYIM_LOG_LINES) {
360                TrophyIM.logging_div.removeChild(
361                TrophyIM.logging_div.firstChild);
362            }
363            var msg_div = document.createElement('div');
364            msg_div.className = 'trophyimlogitem';
365            msg_div.appendChild(document.createTextNode(msg));
366            TrophyIM.logging_div.appendChild(msg_div);
367            TrophyIM.logging_div.scrollTop = TrophyIM.logging_div.scrollHeight;
368        }
369    },
370    /** Function: rawInput
371     *
372     *  This logs the packets actually recieved by strophe at the debug level
373     */
374    rawInput : function (data) {
375        Strophe.debug("RECV: " + data);
376    },
377    /** Function: rawInput
378     *
379     *  This logs the packets actually recieved by strophe at the debug level
380     */
381    rawOutput : function (data) {
382        Strophe.debug("SEND: " + data);
383    },
384    /** Function: login
385     *
386     *  This function logs into server using information given on login page.
387     *  Since the login page is where the logging checkbox is, it makes or
388     *  removes the logging div and cookie accordingly.
389     *
390     */
391    login : function() {
392        if (document.getElementById('trophyimloglevel').checked) {
393            TrophyIM.setCookie('trophyimloglevel', 1);
394            if (!document.getElementById('trophyimlog')) {
395                TrophyIM.client_div.appendChild(DOMObjects.getHTML('loggingDiv'));
396                TrophyIM.logging_div = document.getElementById('trophyimlog');
397            }
398        } else {
399            TrophyIM.delCookie('trophyimloglevel');
400            if (document.getElementById('trophyimlog')) {
401                TrophyIM.client_div.removeChild(document.getElementById(
402                'trophyimlog'));
403                TrophyIM.logging_div = null;
404            }
405        }
406        if (TrophyIM.JSONStore.store_working) { //In case they never logged out
407            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat',
408            'chat_history']);
409        }
410        TrophyIM.connection = new Strophe.Connection(TROPHYIM_BOSH_SERVICE);
411        TrophyIM.connection.rawInput = TrophyIM.rawInput;
412        TrophyIM.connection.rawOutput = TrophyIM.rawOutput;
413        Strophe.log = TrophyIM.log;
414        var barejid  = document.getElementById('trophyimjid').value
415        var fulljid = barejid + '/TrophyIM';
416        TrophyIM.setCookie('trophyimjid', barejid);
417        var password = document.getElementById('trophyimpass').value;
418        var button = document.getElementById('trophyimconnect');
419        if (button.value == 'connect') {
420            button.value = 'disconnect';
421            TrophyIM.connection.connect(fulljid, password, TrophyIM.onConnect);
422        } else {
423            button.value = 'connect';
424            TrophyIM.connection.disconnect();
425        }
426
427    },
428    /** Function: login
429     *
430     *  Logs into fresh session through Strophe, purging any old data.
431     */
432    logout : function()
433        {
434        TrophyIM.delCookie('trophyim_bosh_xid');
435        delete TrophyIM['cookies']['trophyim_bosh_xid'];
436        if (TrophyIM.JSONStore.store_working)
437                {
438            TrophyIM.JSONStore.delData(['groups','roster', 'active_chat', 'chat_history']);
439        }
440       
441                for (var chat in TrophyIM.activeChats['divs'])
442                {
443            delete TrophyIM.activeChats['divs'][chat];
444        }
445               
446        TrophyIM.activeChats = {current: null, divs: {}},
447        TrophyIM.connection.disconnect();
448        TrophyIM.showLogin();
449               
450    },
451    /** Function onConnect
452     *
453     *  Callback given to Strophe upon connection to BOSH proxy.
454     */
455    onConnect : function(status) {
456        if (status == Strophe.Status.CONNECTING) {
457            Strophe.info('Strophe is connecting.');
458        } else if (status == Strophe.Status.CONNFAIL) {
459            Strophe.info('Strophe failed to connect.');
460            TrophyIM.delCookie('trophyim_bosh_xid');
461            TrophyIM.showLogin();
462        } else if (status == Strophe.Status.DISCONNECTING) {
463            Strophe.info('Strophe is disconnecting.');
464        } else if (status == Strophe.Status.DISCONNECTED) {
465            Strophe.info('Strophe is disconnected.');
466            TrophyIM.delCookie('trophyim_bosh_xid');
467            TrophyIM.showLogin();
468        } else if (status == Strophe.Status.CONNECTED) {
469            Strophe.info('Strophe is connected.');
470            TrophyIM.showClient();
471        }
472    },
473
474    /** Function: showClient
475     *
476     *  This clears out the main div and puts in the main client.  It also
477     *  registers all the handlers for Strophe to call in the client.
478     */
479    showClient : function()
480        {
481        TrophyIM.setCookie('trophyim_bosh_xid', TrophyIM.connection.jid + "|" +
482        TrophyIM.connection.sid + "|" +  TrophyIM.connection.rid);
483        var logging_div = TrophyIM.clearClient();
484       
485                loadIM.HTMLSnippets.rosterDiv();
486                loadIM.HTMLSnippets.chatArea();
487               
488                //TrophyIM.client_div.appendChild(DOMObjects.getHTML('rosterDiv'));
489        //TrophyIM.client_div.appendChild(DOMObjects.getHTML('chatArea'));
490        //TrophyIM.client_div.appendChild(DOMObjects.getHTML('statusDiv'));
491               
492        if(logging_div)
493                {
494            TrophyIM.client_div.appendChild(logging_div);
495            TrophyIM.logging_div = document.getElementById('trophyimlog');
496        }
497        TrophyIM.rosterObj = new TrophyIMRoster();
498        TrophyIM.connection.addHandler(TrophyIM.onVersion, Strophe.NS.VERSION,
499        'iq', null, null, null);
500        TrophyIM.connection.addHandler(TrophyIM.onRoster, Strophe.NS.ROSTER,
501        'iq', null, null, null);
502        TrophyIM.connection.addHandler(TrophyIM.onPresence, null, 'presence',
503        null, null, null);
504        TrophyIM.connection.addHandler(TrophyIM.onMessage, null, 'message',
505        null, null,  null);
506        //Get roster then announce presence.
507        TrophyIM.connection.send($iq({type: 'get', xmlns: Strophe.NS.CLIENT}).c(
508        'query', {xmlns: Strophe.NS.ROSTER}).tree());
509        TrophyIM.connection.send($pres().tree());
510        TrophyIM.renderChats();
511        setTimeout("TrophyIM.renderRoster()", 1000);
512    },
513       
514    /** Function: clearClient
515     *
516     *  Clears out client div, preserving and returning existing logging_div if
517     *  one exists
518     */
519    clearClient : function() {
520        if(TrophyIM.logging_div) {
521            var logging_div = TrophyIM.client_div.removeChild(
522            document.getElementById('trophyimlog'));
523        } else {
524            var logging_div = null;
525        }
526        while(TrophyIM.client_div.childNodes.length > 0) {
527            TrophyIM.client_div.removeChild(TrophyIM.client_div.firstChild);
528        }
529        return logging_div;
530    },
531    /** Function: onVersion
532     *
533     *  jabber:iq:version query handler
534     */
535    onVersion : function(msg) {
536        Strophe.debug("Version handler");
537        if (msg.getAttribute('type') == 'get') {
538            var from = msg.getAttribute('from');
539            var to = msg.getAttribute('to');
540            var id = msg.getAttribute('id');
541            var reply = $iq({type: 'result', to: from, from: to, id: id}).c('query',
542            {name: "TrophyIM", version: TROPHYIM_VERSION, os:
543            "Javascript-capable browser"});
544            TrophyIM.connection.send(reply.tree());
545        }
546        return true;
547    },
548    /** Function: onRoster
549     *
550     *  Roster iq handler
551     */
552    onRoster : function(msg) {
553        Strophe.debug("Roster handler");
554        var roster_items = msg.firstChild.getElementsByTagName('item');
555        for (var i = 0; i < roster_items.length; i++) {
556            var groups = roster_items[i].getElementsByTagName('group');
557            var group_array = new Array();
558            for (var g = 0; g < groups.length; g++) {
559                group_array[group_array.length] =
560                groups[g].firstChild.nodeValue;
561            }
562            TrophyIM.rosterObj.addContact(roster_items[i].getAttribute('jid'),
563            roster_items[i].getAttribute('subscription'),
564            roster_items[i].getAttribute('name'), group_array);
565        }
566        if (msg.getAttribute('type') == 'set') {
567            TrophyIM.connection.send($iq({type: 'reply', id:
568            msg.getAttribute('id'), to: msg.getAttribute('from')}).tree());
569        }
570        return true;
571    },
572    /** Function: onPresence
573     *
574     *  Presence handler
575     */
576    onPresence : function(msg) {
577        Strophe.debug("Presence handler");
578        var type = msg.getAttribute('type') ? msg.getAttribute('type') :
579        'available';
580        var show = msg.getElementsByTagName('show').length ? Strophe.getText(
581        msg.getElementsByTagName('show')[0]) : type;
582        var status = msg.getElementsByTagName('status').length ? Strophe.getText(
583        msg.getElementsByTagName('status')[0]) : '';
584        var priority = msg.getElementsByTagName('priority').length ? parseInt(
585        Strophe.getText(msg.getElementsByTagName('priority')[0])) : 0;
586        TrophyIM.rosterObj.setPresence(msg.getAttribute('from'), priority,
587        show, status);
588        return true;
589    },
590    /** Function: onMessage
591     *
592     *  Message handler
593     */
594    onMessage : function(msg) {
595        Strophe.debug("Message handler");
596        var from = msg.getAttribute('from');
597        var type = msg.getAttribute('type');
598        var elems = msg.getElementsByTagName('body');
599
600        if ((type == 'chat' || type == 'normal') && elems.length > 0) {
601            var barejid = Strophe.getBareJidFromJid(from);
602            var jid_lower = barejid.toLowerCase();
603            var contact = TrophyIM.rosterObj.roster[barejid.toLowerCase()]['contact'];
604            if (contact) { //Do we know you?
605                if (contact['name'] != null) {
606                    message  = contact['name'] + " (" + barejid + "): ";
607                } else {
608                    message = contact['jid'] + ": ";
609                }
610                message += Strophe.getText(elems[0]);
611                TrophyIM.makeChat(from); //Make sure we have a chat window
612                TrophyIM.addMessage(message, jid_lower);
613                if (TrophyIM.activeChats['current'] != jid_lower) {
614                    TrophyIM.activeChats['divs'][jid_lower][
615                    'tab'].className = "trophyimchattab trophyimchattab_a";
616                    TrophyIM.setTabPresence(from,
617                    TrophyIM.activeChats['divs'][jid_lower]['tab']);
618                }
619            }
620        }
621        return true;
622    },
623    /** Function: makeChat
624     *
625     *  Make sure chat window to given fulljid exists, switching chat context to
626     *  given resource
627     */
628    makeChat : function(fulljid) {
629        var barejid = Strophe.getBareJidFromJid(fulljid);
630        if (!TrophyIM.activeChats['divs'][barejid]) {
631            var chat_tabs = document.getElementById('trophyimchattabs');
632            var chat_tab = DOMObjects.getHTML('chatTab');
633            var chat_box = DOMObjects.getHTML('chatBox');
634            var contact = TrophyIM.rosterObj.getContact(barejid);
635            var tab_name = (contact['name'] != null) ? contact['name'] : barejid;
636            chat_tab.className = "trophyimchattab trophyimchattab_a";
637            getElementsByClassName('trophyimchattabjid', 'div',
638            chat_tab)[0].appendChild(document.createTextNode(barejid));
639            getElementsByClassName('trophyimchattabname', 'div',
640            chat_tab)[0].appendChild(document.createTextNode(tab_name));
641            chat_tab = chat_tabs.appendChild(chat_tab);
642            TrophyIM.activeChats['divs'][barejid] = {jid:fulljid, tab:chat_tab,
643            box:chat_box};
644            if (!TrophyIM.activeChats['current']) { //We're the first
645                TrophyIM.activeChats['current'] = barejid;
646                document.getElementById('trophyimchat').appendChild(chat_box);
647                TrophyIM.activeChats['divs'][barejid]['box'] = chat_box;
648                TrophyIM.activeChats['divs'][barejid]['tab'].className =
649                "trophyimchattab trophyimchattab_f";
650            }
651            if (!TrophyIM.chatHistory[barejid.toLowerCase()]) {
652                TrophyIM.chatHistory[barejid.toLowerCase()] = {resource: null,
653                history: new Array()};
654            }
655            TrophyIM.setTabPresence(fulljid, chat_tab);
656        }
657        TrophyIM.activeChats['divs'][barejid.toLowerCase()]['resource'] =
658        Strophe.getResourceFromJid(fulljid);
659        TrophyIM.chatHistory[barejid.toLowerCase()]['resource'] =
660        Strophe.getResourceFromJid(fulljid);
661    },
662    /** Function showChat
663     *
664     *  Make chat box to given barejid active
665     */
666    showChat : function(barejid) {
667        if (TrophyIM.activeChats['current'] &&
668        TrophyIM.activeChats['current'] != barejid) {
669            var chat_area = document.getElementById('trophyimchat');
670            var active_divs =
671            TrophyIM.activeChats['divs'][TrophyIM.activeChats['current']];
672            active_divs['box'] =
673            chat_area.removeChild(getElementsByClassName('trophyimchatbox',
674            'div', chat_area)[0].parentNode);
675            active_divs['tab'].className = "trophyimchattab trophyimchattab_b";
676            TrophyIM.setTabPresence(TrophyIM.activeChats['current'],
677            active_divs['tab']);
678            TrophyIM.activeChats['divs'][barejid]['box'] =
679            chat_area.appendChild(TrophyIM.activeChats['divs'][barejid]['box']);
680            TrophyIM.activeChats['current'] = barejid;
681            TrophyIM.activeChats['divs'][barejid]['tab'].className =
682            "trophyimchattab trophyimchattab_f";
683            TrophyIM.setTabPresence(barejid,
684            TrophyIM.activeChats['divs'][barejid]['tab']);
685            getElementsByClassName('trophyimchatinput', null,
686            TrophyIM.activeChats['divs'][barejid]['box'])[0].focus();
687        }
688    },
689    /** Function: setTabPresence
690     *
691     *  Applies appropriate class to tab div based on presence
692     *
693     *  Parameters:
694     *    (String) jid - jid to check presence for
695     *    (String) tab_div - tab div element to alter class on
696     */
697    setTabPresence : function(jid, tab_div) {
698        var presence = TrophyIM.rosterObj.getPresence(jid);
699        tab_div.className = tab_div.className.replace(" trophyimchattab_av", "");
700        tab_div.className = tab_div.className.replace(" trophyimchattab_aw", "");
701        tab_div.className = tab_div.className.replace(" trophyimchattab_off", "");
702        if (presence) {
703            if (presence['show'] == "chat" || presence['show'] == "available") {
704                tab_div.className += " trophyimchattab_av";
705            } else {
706                tab_div.className += " trophyimchattab_aw";
707            }
708        } else {
709            tab_div.className += " trophyimchattab_off";
710        }
711    },
712    /** Function: addMessage
713     *
714     *  Adds message to chat box, and history
715     *
716     *  Parameters:
717     *    (string) msg - the message to add
718     *    (string) jid - the jid of chat box to add the message to.
719     */
720    addMessage : function(msg, jid) {
721        var chat_box = getElementsByClassName('trophyimchatbox', 'div',
722        TrophyIM.activeChats['divs'][jid]['box'])[0];
723        var msg_div = document.createElement('div');
724        msg_div.className = 'trophyimchatmessage';
725        msg_div.appendChild(document.createTextNode(msg));
726        chat_box.appendChild(msg_div);
727        chat_box.scrollTop = chat_box.scrollHeight;
728        if (TrophyIM.chatHistory[jid]['history'].length > 10) {
729            TrophyIM.chatHistory[jid]['history'].shift();
730        }
731        TrophyIM.chatHistory[jid]['history'][
732        TrophyIM.chatHistory[jid]['history'].length] = msg;
733    },
734    /** Function: renderRoster
735     *
736     *  Renders roster, looking only for jids flagged by setPresence as having
737     *  changed.
738     */
739    renderRoster : function() {
740        if (TrophyIM.rosterObj.changes.length > 0) {
741            var roster_div = document.getElementById('trophyimroster');
742            if(roster_div) {
743                var groups = new Array();
744                for (var group in TrophyIM.rosterObj.groups) {
745                    groups[groups.length] = group;
746                }
747                groups.sort();
748                var group_divs = getElementsByClassName('trophyimrostergroup',
749                null, roster_div);
750                for (var g = 0; g < group_divs.length; g++) {
751                    var group_name = getElementsByClassName('trophyimrosterlabel',
752                    null, group_divs[g])[0].firstChild.nodeValue;
753                    while (group_name > groups[0]) {
754                        var new_group = TrophyIM.renderGroup(groups[0], roster_div);
755                        new_group = roster_div.insertBefore(new_group,
756                        group_divs[g]);
757                        if (TrophyIM.rosterObj.groupHasChanges(groups[0])) {
758                            TrophyIM.renderGroupUsers(new_group, groups[0],
759                            TrophyIM.rosterObj.changes.slice());
760                        }
761                        groups.shift();
762                    }
763                    if (group_name == groups[0]) {
764                        groups.shift();
765                    }
766                    if (TrophyIM.rosterObj.groupHasChanges(group_name)) {
767                        TrophyIM.renderGroupUsers(group_divs[g], group_name,
768                        TrophyIM.rosterObj.changes.slice());
769                    }
770                }
771                while (groups.length) {
772                    var group_name = groups.shift();
773                    var new_group = TrophyIM.renderGroup(group_name,
774                    roster_div);
775                    new_group = roster_div.appendChild(new_group);
776                    if (TrophyIM.rosterObj.groupHasChanges(group_name)) {
777                        TrophyIM.renderGroupUsers(new_group, group_name,
778                        TrophyIM.rosterObj.changes.slice());
779                    }
780                }
781            }
782            TrophyIM.rosterObj.changes = new Array();
783            TrophyIM.constants.stale_roster = false;
784        }
785        setTimeout("TrophyIM.renderRoster()", 1000);
786    },
787    /** Function: renderChats
788    *
789    *  Renders chats found in TrophyIM.chatHistory.  Called upon page reload.
790    *  Waits for stale_roster flag to clear before trying to run, so that the
791    *  roster exists
792    */
793    renderChats : function() {
794        if (TrophyIM.constants.stale_roster == false) {
795            if(TrophyIM.JSONStore.store_working) {
796                var data = TrophyIM.JSONStore.getData(['chat_history',
797                'active_chat']);
798                if (data['active_chat']) {
799                    for (var jid in data['chat_history']) {
800                        fulljid = jid + "/" + data['chat_history'][jid]['resource'];
801                        Strophe.info("Makechat " + fulljid);
802                        TrophyIM.makeChat(fulljid);
803                        for (var h = 0; h <
804                        data['chat_history'][jid]['history'].length; h++) {
805                            TrophyIM.addMessage(data['chat_history'][jid]['history'][h],
806                            jid);
807                        }
808                    }
809                    TrophyIM.chat_history = data['chat_history'];
810                    TrophyIM.showChat(data['active_chat']);
811                }
812            }
813        } else {
814            setTimeout("TrophyIM.renderChats()", 1000);
815        }
816    },
817    /** Function: renderGroup
818     *
819     *  Renders actual group label in roster
820     *
821     *  Parameters:
822     *    (String) group - name of group to render
823     *    (DOM) roster_div - roster div
824     *
825     *  Returns:
826     *    DOM group div to append into roster
827     */
828    renderGroup : function(group, roster_div) {
829        var new_group = DOMObjects.getHTML('rosterGroup');
830        var label_div = getElementsByClassName( 'trophyimrosterlabel', null,
831        new_group)[0];
832        label_div.appendChild(document.createTextNode(group));
833        new_group.appendChild(label_div);
834        return new_group;
835    },
836    /** Function: renderGroupUsers
837     *
838     *  Re-renders user entries in given group div based on status of roster
839     *
840     *  Parameter: (Array) changes - jids with changes in the roster.  Note:
841     *  renderGroupUsers will clobber this.
842     */
843    renderGroupUsers : function(group_div, group_name, changes) {
844        var group_members = TrophyIM.rosterObj.groups[group_name];
845        var member_divs = getElementsByClassName('trophyimrosteritem', null,
846        group_div);
847        for (var m = 0; m < member_divs.length; m++) {
848            member_jid = getElementsByClassName('trophyimrosterjid', null,
849            member_divs[m])[0].firstChild.nodeValue;
850            if (member_jid > changes[0]) {
851                if (changes[0] in group_members) {
852                    var new_presence = TrophyIM.rosterObj.getPresence(
853                    changes[0]);
854                    if(new_presence) {
855                        var new_member = DOMObjects.getHTML('rosterItem');
856                        var new_contact =
857                        TrophyIM.rosterObj.getContact(changes[0]);
858                        getElementsByClassName('trophyimrosterjid', null,
859                        new_member)[0].appendChild(document.createTextNode(
860                        changes[0]));
861                        var new_name = (new_contact['name'] != null) ?
862                        new_contact['name'] : changes[0];
863                        getElementsByClassName('trophyimrostername', null,
864                        new_member)[0].appendChild(document.createTextNode(
865                        new_name));
866                        group_div.insertBefore(new_member, member_divs[m]);
867                        if (new_presence['show'] == "available" ||
868                        new_presence['show'] == "chat") {
869                            new_member.className =
870                            "trophyimrosteritem trophyimrosteritem_av";
871                        } else {
872                            new_member.className =
873                            "trophyimrosteritem trophyimrosteritem_aw";
874                        }
875                    } else {
876                        //show offline contacts
877                    }
878                }
879                changes.shift();
880            } else if (member_jid == changes[0]) {
881                member_presence = TrophyIM.rosterObj.getPresence(member_jid);
882                if(member_presence) {
883                    if (member_presence['show'] == "available" ||
884                    member_presence['show'] == "chat") {
885                        member_divs[m].className =
886                        "trophyimrosteritem trophyimrosteritem_av";
887                    } else {
888                        member_divs[m].className =
889                        "trophyimrosteritem trophyimrosteritem_aw";
890                    }
891                } else {
892                    //show offline status
893                    group_div.removeChild(member_divs[m]);
894                }
895                changes.shift();
896            }
897        }
898        while (changes.length > 0) {
899            if (changes[0] in group_members) {
900                var new_presence = TrophyIM.rosterObj.getPresence(changes[0]);
901                if(new_presence) {
902                    var new_member = DOMObjects.getHTML('rosterItem');
903                    var new_contact =
904                    TrophyIM.rosterObj.getContact(changes[0]);
905                    getElementsByClassName('trophyimrosterjid', null,
906                    new_member)[0].appendChild(document.createTextNode(
907                    changes[0]));
908                    var new_name = (new_contact['name'] != null) ?
909                    new_contact['name'] : changes[0];
910                    getElementsByClassName('trophyimrostername', null,
911                    new_member)[0].appendChild(document.createTextNode(
912                    new_name));
913                    group_div.appendChild(new_member);
914                    if (new_presence['show'] == "available" ||
915                    new_presence['show'] == "chat") {
916                        new_member.className =
917                        "trophyimrosteritem trophyimrosteritem_av";
918                    } else {
919                        new_member.className =
920                        "trophyimrosteritem trophyimrosteritem_aw";
921                    }
922                } else {
923                    //show offline
924                }
925            }
926            changes.shift();
927        }
928    },
929    /** Function: rosterClick
930     *
931     *  Handles actions when a roster item is clicked
932     */
933    rosterClick : function(roster_item) {
934        var barejid = getElementsByClassName('trophyimrosterjid', null,
935        roster_item)[0].firstChild.nodeValue;
936        var presence = TrophyIM.rosterObj.getPresence(barejid);
937        if (presence && presence['resource']) {
938            var fulljid = barejid + "/" + presence['resource'];
939        } else {
940            var fulljid = barejid;
941        }
942        TrophyIM.makeChat(fulljid);
943        TrophyIM.showChat(barejid);
944    },
945    /** Function: tabClick
946     *
947     *  Handles actions when a chat tab is clicked
948     */
949    tabClick : function(tab_item) {
950        var barejid = getElementsByClassName('trophyimchattabjid', null,
951        tab_item)[0].firstChild.nodeValue;
952        if (TrophyIM.activeChats['divs'][barejid]) {
953            TrophyIM.showChat(barejid);
954        }
955    },
956    /** Function: tabClose
957     *
958     *  Closes chat tab
959     */
960    tabClose : function(tab_item) {
961        var barejid = getElementsByClassName('trophyimchattabjid', null,
962        tab_item.parentNode)[0].firstChild.nodeValue;
963        if (TrophyIM.activeChats['current'] == barejid) {
964            if (tab_item.parentNode.nextSibling) {
965                TrophyIM.showChat(getElementsByClassName('trophyimchattabjid',
966                null, tab_item.parentNode.nextSibling)[0].firstChild.nodeValue);
967            } else if (tab_item.parentNode.previousSibling) {
968                TrophyIM.showChat(getElementsByClassName('trophyimchattabjid',
969                null, tab_item.parentNode.previousSibling)[0].firstChild.nodeValue);
970            } else { //no other active chat
971                document.getElementById('trophyimchat').removeChild(
972                getElementsByClassName('trophyimchatbox')[0].parentNode);
973                delete TrophyIM.activeChats['current'];
974            }
975        }
976        delete TrophyIM.activeChats['divs'][barejid];
977        delete TrophyIM.chatHistory[barejid];
978        //delete tab
979        tab_item.parentNode.parentNode.removeChild(tab_item.parentNode);
980    },
981    /** Function: sendMessage
982     *
983     *  Send message from chat input to user
984     */
985    sendMessage : function(chat_box) {
986        var message_input =
987        getElementsByClassName('trophyimchatinput', null,
988        chat_box.parentNode)[0];
989        var active_jid = TrophyIM.activeChats['current'];
990        if(TrophyIM.activeChats['current']) {
991            var active_chat =
992            TrophyIM.activeChats['divs'][TrophyIM.activeChats['current']];
993            var to = TrophyIM.activeChats['current'];
994            if (active_chat['resource']) {
995                to += "/" + active_chat['resource'];
996            }
997            TrophyIM.connection.send($msg({to: to, from:
998            TrophyIM.connection.jid, type: 'chat'}).c('body').t(
999            message_input.value).tree());
1000            TrophyIM.addMessage("Me:\n" + message_input.value,
1001            TrophyIM.activeChats['current']);
1002        }
1003        message_input.value = '';
1004        message_input.focus();
1005    }
1006};
1007
1008/** Class: TrophyIMRoster
1009 *
1010 *
1011 *  This object stores the roster and presence info for the TrophyIMClient
1012 *
1013 *  roster[jid_lower]['contact']
1014 *  roster[jid_lower]['presence'][resource]
1015 */
1016function TrophyIMRoster() {
1017    /** Constants: internal arrays
1018     *    (Object) roster - the actual roster/presence information
1019     *    (Object) groups - list of current groups in the roster
1020     *    (Array) changes - array of jids with presence changes
1021     */
1022    if (TrophyIM.JSONStore.store_working) {
1023        var data = TrophyIM.JSONStore.getData(['roster', 'groups']);
1024        this.roster = (data['roster'] != null) ? data['roster'] : {};
1025        this.groups = (data['groups'] != null) ? data['groups'] : {};
1026    } else {
1027        this.roster = {};
1028        this.groups = {};
1029    }
1030    this.changes = new Array();
1031    if (TrophyIM.constants.stale_roster) {
1032        for (var jid in this.roster) {
1033            this.changes[this.changes.length] = jid;
1034        }
1035    }
1036    /** Function: addContact
1037     *
1038     *  Adds given contact to roster
1039     *
1040     *  Parameters:
1041     *    (String) jid - bare jid
1042     *    (String) subscription - subscription attribute for contact
1043     *    (String) name - name attribute for contact
1044     *    (Array) groups - array of groups contact is member of
1045     */
1046    this.addContact = function(jid, subscription, name, groups) {
1047        var contact = {jid:jid, subscription:subscription, name:name, groups:groups}
1048        var jid_lower = jid.toLowerCase();
1049        if (this.roster[jid_lower]) {
1050            this.roster[jid_lower]['contact'] = contact;
1051        } else {
1052            this.roster[jid_lower] = {contact:contact};
1053        }
1054        groups = groups ? groups : [''];
1055        for (var g = 0; g < groups.length; g++) {
1056            if (!this.groups[groups[g]]) {
1057                this.groups[groups[g]] = {};
1058            }
1059            this.groups[groups[g]][jid_lower] = jid_lower;
1060        }
1061    }
1062    /** Function: getContact
1063     *
1064     *  Returns contact entry for given jid
1065     *
1066     *  Parameter: (String) jid - jid to return
1067     */
1068    this.getContact = function(jid) {
1069        if (this.roster[jid.toLowerCase()]) {
1070            return this.roster[jid.toLowerCase()]['contact'];
1071        }
1072    }
1073    /** Function: setPresence
1074     *
1075     *  Sets presence
1076     *
1077     *  Parameters:
1078     *    (String) fulljid: full jid with presence
1079     *    (Integer) priority: priority attribute from presence
1080     *    (String) show: show attribute from presence
1081     *    (String) status: status attribute from presence
1082     */
1083    this.setPresence = function(fulljid, priority, show, status) {
1084        var barejid = Strophe.getBareJidFromJid(fulljid);
1085        var resource = Strophe.getResourceFromJid(fulljid);
1086        var jid_lower = barejid.toLowerCase();
1087        if(show != 'unavailable') {
1088            if (!this.roster[jid_lower]) {
1089                this.addContact(barejid, 'not-in-roster');
1090            }
1091            var presence = {
1092                resource:resource, priority:priority, show:show, status:status
1093            }
1094            if (!this.roster[jid_lower]['presence']) {
1095                this.roster[jid_lower]['presence'] = {}
1096            }
1097            this.roster[jid_lower]['presence'][resource] = presence
1098        } else if (this.roster[jid_lower] && this.roster[jid_lower]['presence']
1099        && this.roster[jid_lower]['presence'][resource]) {
1100            delete this.roster[jid_lower]['presence'][resource];
1101        }
1102        this.addChange(jid_lower);
1103        if (TrophyIM.activeChats['divs'][jid_lower]) {
1104            TrophyIM.setTabPresence(jid_lower,
1105            TrophyIM.activeChats['divs'][jid_lower]['tab']);
1106        }
1107    }
1108    /** Function: addChange
1109     *
1110     *  Adds given jid to this.changes, keeping this.changes sorted and
1111     *  preventing duplicates.
1112     *
1113     *  Parameters
1114     *    (String) jid : jid to add to this.changes
1115     */
1116    this.addChange = function(jid) {
1117        for (var c = 0; c < this.changes.length; c++) {
1118            if (this.changes[c] == jid) {
1119                return;
1120            }
1121        }
1122        this.changes[this.changes.length] = jid;
1123        this.changes.sort();
1124    }
1125    /** Function: getPresence
1126     *
1127     *  Returns best presence for given jid as Array(resource, priority, show,
1128     *  status)
1129     *
1130     *  Parameter: (String) fulljid - jid to return best presence for
1131     */
1132    this.getPresence = function(fulljid) {
1133        var jid = Strophe.getBareJidFromJid(fulljid);
1134        var current = null;
1135        if (this.roster[jid.toLowerCase()] &&
1136        this.roster[jid.toLowerCase()]['presence']) {
1137            for (var resource in this.roster[jid.toLowerCase()]['presence']) {
1138                var presence = this.roster[jid.toLowerCase()]['presence'][resource];
1139                if (current == null) {
1140                    current = presence
1141                } else {
1142                    if(presence['priority'] > current['priority'] && ((presence['show'] == "chat"
1143                    || presence['show'] == "available") || (current['show'] != "chat" ||
1144                    current['show'] != "available"))) {
1145                        current = presence
1146                    }
1147                }
1148            }
1149        }
1150        return current;
1151    }
1152    /** Function: groupHasChanges
1153     *
1154     *  Returns true if current group has members in this.changes
1155     *
1156     *  Parameters:
1157     *    (String) group - name of group to check
1158     */
1159    this.groupHasChanges = function(group) {
1160        for (var c = 0; c < this.changes.length; c++) {
1161            if (this.groups[group][this.changes[c]]) {
1162                return true;
1163            }
1164        }
1165        return false;
1166    }
1167    /** Fuction: save
1168     *
1169     *  Saves roster data to JSON store
1170     */
1171    this.save = function() {
1172        if (TrophyIM.JSONStore.store_working) {
1173            TrophyIM.JSONStore.setData({roster:this.roster,
1174            groups:this.groups, active_chat:TrophyIM.activeChats['current'],
1175            chat_history:TrophyIM.chatHistory});
1176        }
1177    }
1178}
1179/** Class: TrophyIMJSONStore
1180 *
1181 *
1182 *  This object is the mechanism by which TrophyIM stores and retrieves its
1183 *  variables from the url provided by TROPHYIM_JSON_STORE
1184 *
1185 */
1186function TrophyIMJSONStore() {
1187    this.store_working = false;
1188    /** Function _newXHR
1189     *
1190     *  Set up new cross-browser xmlhttprequest object
1191     *
1192     *  Parameters:
1193     *    (function) handler = what to set onreadystatechange to
1194     */
1195     this._newXHR = function (handler) {
1196        var xhr = null;
1197        if (window.XMLHttpRequest) {
1198            xhr = new XMLHttpRequest();
1199            if (xhr.overrideMimeType) {
1200            xhr.overrideMimeType("text/xml");
1201            }
1202        } else if (window.ActiveXObject) {
1203            xhr = new ActiveXObject("Microsoft.XMLHTTP");
1204        }
1205        return xhr;
1206    }
1207    /** Function getData
1208     *  Gets data from JSONStore
1209     *
1210     *  Parameters:
1211     *    (Array) vars = Variables to get from JSON store
1212     *
1213     *  Returns:
1214     *    Object with variables indexed by names given in parameter 'vars'
1215     */
1216    this.getData = function(vars) {
1217        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1218            Strophe.debug("Retrieving JSONStore data");
1219            var xhr = this._newXHR();
1220            var getdata = "get=" + vars.join(",");
1221            try {
1222                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1223            } catch (e) {
1224                Strophe.error("JSONStore open failed.");
1225                return false;
1226            }
1227            xhr.setRequestHeader('Content-type',
1228            'application/x-www-form-urlencoded');
1229            xhr.setRequestHeader('Content-length', getdata.length);
1230            xhr.send(getdata);
1231            if (xhr.readyState == 4 && xhr.status == 200) {
1232                try {
1233                    var dataObj = JSON.parse(xhr.responseText);
1234                    return this.emptyFix(dataObj);
1235                } catch(e) {
1236                    Strophe.error("Could not parse JSONStore response" +
1237                    xhr.responseText);
1238                    return false;
1239                }
1240            } else {
1241                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1242                return false;
1243            }
1244        }
1245    }
1246    /** Function emptyFix
1247     *    Fix for bugs in external JSON implementations such as
1248     *    http://bugs.php.net/bug.php?id=41504.
1249     *    A.K.A. Don't use PHP, people.
1250     */
1251    this.emptyFix = function(obj) {
1252        if (typeof(obj) == "object") {
1253            for (var i in obj) {
1254                if (i == '_empty_') {
1255                    obj[""] = this.emptyFix(obj['_empty_']);
1256                    delete obj['_empty_'];
1257                } else {
1258                    obj[i] = this.emptyFix(obj[i]);
1259                }
1260            }
1261        }
1262        return obj
1263    }
1264    /** Function delData
1265     *    Deletes data from JSONStore
1266     *
1267     *  Parameters:
1268     *    (Array) vars  = Variables to delete from JSON store
1269     *
1270     *  Returns:
1271     *    Status of delete attempt.
1272     */
1273    this.delData = function(vars) {
1274        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1275            Strophe.debug("Retrieving JSONStore data");
1276            var xhr = this._newXHR();
1277            var deldata = "del=" + vars.join(",");
1278            try {
1279                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1280            } catch (e) {
1281                Strophe.error("JSONStore open failed.");
1282                return false;
1283            }
1284            xhr.setRequestHeader('Content-type',
1285            'application/x-www-form-urlencoded');
1286            xhr.setRequestHeader('Content-length', deldata.length);
1287            xhr.send(deldata);
1288            if (xhr.readyState == 4 && xhr.status == 200) {
1289                try {
1290                    var dataObj = JSON.parse(xhr.responseText);
1291                    return dataObj;
1292                } catch(e) {
1293                    Strophe.error("Could not parse JSONStore response");
1294                    return false;
1295                }
1296            } else {
1297                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1298                return false;
1299            }
1300        }
1301    }
1302    /** Function setData
1303     *    Stores data in JSONStore, overwriting values if they exist
1304     *
1305     *  Parameters:
1306     *    (Object) vars : Object containing named vars to store ({name: value,
1307     *    othername: othervalue})
1308     *
1309     *  Returns:
1310     *    Status of storage attempt
1311     */
1312    this.setData = function(vars) {
1313        if (typeof(TROPHYIM_JSON_STORE) != undefined) {
1314            Strophe.debug("Storing JSONStore data");
1315            var senddata = "set=" + JSON.stringify(vars);
1316            var xhr = this._newXHR();
1317            try {
1318                xhr.open("POST", TROPHYIM_JSON_STORE, false);
1319            } catch (e) {
1320                Strophe.error("JSONStore open failed.");
1321                return false;
1322            }
1323            xhr.setRequestHeader('Content-type',
1324            'application/x-www-form-urlencoded');
1325            xhr.setRequestHeader('Content-length', senddata.length);
1326            xhr.send(senddata);
1327            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText ==
1328            "OK") {
1329                return true;
1330            } else {
1331                Strophe.error("JSONStore open failed. Status: " + xhr.status);
1332                return false;
1333            }
1334        }
1335    }
1336    var testData = true;
1337    if (this.setData({testData:testData})) {
1338        var testResult = this.getData(['testData']);
1339        if (testResult && testResult['testData'] == true) {
1340            this.store_working = true;
1341        }
1342    }
1343}
1344/** Constants: Node types
1345 *
1346 * Implementations of constants that IE doesn't have, but we need.
1347 */
1348if (document.ELEMENT_NODE == null) {
1349    document.ELEMENT_NODE = 1;
1350    document.ATTRIBUTE_NODE = 2;
1351    document.TEXT_NODE = 3;
1352    document.CDATA_SECTION_NODE = 4;
1353    document.ENTITY_REFERENCE_NODE = 5;
1354    document.ENTITY_NODE = 6;
1355    document.PROCESSING_INSTRUCTION_NODE = 7;
1356    document.COMMENT_NODE = 8;
1357    document.DOCUMENT_NODE = 9;
1358    document.DOCUMENT_TYPE_NODE = 10;
1359    document.DOCUMENT_FRAGMENT_NODE = 11;
1360    document.NOTATION_NODE = 12;
1361}
1362
1363/** Function: importNode
1364 *
1365 *  document.importNode implementation for IE, which doesn't have importNode
1366 *
1367 *  Parameters:
1368 *    (Object) node - dom object
1369 *    (Boolean) allChildren - import node's children too
1370 */
1371if (!document.importNode) {
1372    document.importNode = function(node, allChildren) {
1373        switch (node.nodeType) {
1374            case document.ELEMENT_NODE:
1375                var newNode = document.createElement(node.nodeName);
1376                if (node.attributes && node.attributes.length > 0) {
1377                    for(var i = 0; i < node.attributes.length; i++) {
1378                        newNode.setAttribute(node.attributes[i].nodeName,
1379                        node.getAttribute(node.attributes[i].nodeName));
1380                    }
1381                }
1382                if (allChildren && node.childNodes &&
1383                node.childNodes.length > 0) {
1384                    for (var i = 0; i < node.childNodes.length; i++) {
1385                        newNode.appendChild(document.importNode(
1386                        node.childNodes[i], allChildren));
1387                    }
1388                }
1389                return newNode;
1390                break;
1391            case document.TEXT_NODE:
1392            case document.CDATA_SECTION_NODE:
1393            case document.COMMENT_NODE:
1394                return document.createTextNode(node.nodeValue);
1395                break;
1396        }
1397    };
1398}
1399
1400/** Function: getElementsByClassName
1401 *
1402 *  DOMObject.getElementsByClassName implementation for browsers that don't
1403 *  support it yet.
1404 *
1405 *  Developed by Robert Nyman, http://www.robertnyman.com
1406 *  Code/licensing: http://code.google.com/p/getelementsbyclassname/
1407*/
1408var getElementsByClassName = function (className, tag, elm){
1409    if (document.getElementsByClassName) {
1410        getElementsByClassName = function (className, tag, elm) {
1411            elm = elm || document;
1412            var elements = elm.getElementsByClassName(className),
1413                nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
1414                returnElements = [],
1415                current;
1416            for(var i=0, il=elements.length; i<il; i+=1){
1417                current = elements[i];
1418                if(!nodeName || nodeName.test(current.nodeName)) {
1419                    returnElements.push(current);
1420                }
1421            }
1422            return returnElements;
1423        };
1424    } else if (document.evaluate) {
1425        getElementsByClassName = function (className, tag, elm) {
1426            tag = tag || "*";
1427            elm = elm || document;
1428            var classes = className.split(" "),
1429                classesToCheck = "",
1430                xhtmlNamespace = "http://www.w3.org/1999/xhtml",
1431                namespaceResolver = (document.documentElement.namespaceURI ===
1432                    xhtmlNamespace)? xhtmlNamespace : null,
1433                returnElements = [],
1434                elements,
1435                node;
1436            for(var j=0, jl=classes.length; j<jl; j+=1){
1437                classesToCheck += "[contains(concat(' ', @class, ' '), ' " +
1438                    classes[j] + " ')]";
1439            }
1440            try {
1441                elements = document.evaluate(".//" + tag + classesToCheck,
1442                    elm, namespaceResolver, 0, null);
1443            } catch (e) {
1444                elements = document.evaluate(".//" + tag + classesToCheck,
1445                    elm, null, 0, null);
1446            }
1447            while ((node = elements.iterateNext())) {
1448                returnElements.push(node);
1449            }
1450            return returnElements;
1451        };
1452    } else {
1453        getElementsByClassName = function (className, tag, elm) {
1454            tag = tag || "*";
1455            elm = elm || document;
1456            var classes = className.split(" "),
1457                classesToCheck = [],
1458                elements = (tag === "*" && elm.all)? elm.all :
1459                     elm.getElementsByTagName(tag),
1460                current,
1461                returnElements = [],
1462                match;
1463            for(var k=0, kl=classes.length; k<kl; k+=1){
1464                classesToCheck.push(new RegExp("(^|\\s)" + classes[k] +
1465                    "(\\s|$)"));
1466            }
1467            for(var l=0, ll=elements.length; l<ll; l+=1){
1468                current = elements[l];
1469                match = false;
1470                for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
1471                    match = classesToCheck[m].test(current.className);
1472                    if (!match) {
1473                        break;
1474                    }
1475                }
1476                if (match) {
1477                    returnElements.push(current);
1478                }
1479            }
1480            return returnElements;
1481        };
1482    }
1483    return getElementsByClassName(className, tag, elm);
1484};
1485
1486/**
1487 *
1488 * Bootstrap self into window.onload and window.onunload
1489 */
1490var oldonload = window.onload;
1491window.onload = function() {
1492    if(oldonload) {
1493        oldonload();
1494    }
1495    TrophyIM.load();
1496};
1497var oldonunload = window.onunload;
1498window.onunload = function() {
1499    if(oldonunload) {
1500        oldonunload();
1501    }
1502    TrophyIM.storeData();
1503}
Note: See TracBrowser for help on using the repository browser.