

/*
Inter Window Communcations Library
$Id $

Copyright (c) 2006, David Davis
All rights reserved.

FEATURES
* This library can deliver pseudo events across windows/tabs
* Browsers Supported
 * IE 5.1+
 * FireFox 2+
* Not Supported
 * All others, including Firefox 1

BUGS
* Event IDs can be duped, but I haven't seen lost events yet.

TODO
* Firefox 1 compatability
* Maybe add a fallback using cookies or flash

NOTES
* This has only been tested on firefox 2 and IE 6

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.

    * Neither the name of "Cometd" nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

IWC = new Class( Observer, {

    NAMESPACE: "core-", /* don't use colons, because of IE */
    CLEANUP_TIMER: 3000, /* ms */


    init: function( data ) {
        if ( !data )
            data = {};
        
        /* TODO uuid / guid */
        if ( !data.clientID )
            data.clientID = Math.random() * 10000 + 10000;
        
        this.clientID = data.clientID;
        
        var domain = document.domain.split( '.' );
        domain = domain.reverse();
        if ( domain.length > 1 && !domain[ 0 ].match( /^\d+$/ ) )
            domain = [ domain[ 0 ], domain[ 1 ] ];
        domain = domain.reverse().join( '.' );

        log.debug('storage domain: '+domain);

        /* TODO non firefox 2+ */
        this.storage = ( window.globalStorage )
            ? new WhatWGStorage( domain, this.getIndirectMethod( "eventStorage" ) )
            : new IEPersistentStorage( domain, this.getIndirectMethod( "eventStorage" ) );
            
        this.eventID = parseInt( this.storage.getItem( this.NAMESPACE + "iwc-eid" ) );
        if ( !this.eventID )
            this.storage.setItem( this.NAMESPACE + "iwc-eid", this.eventID = 1 );

        var val = this.storage.getItem( this.NAMESPACE + "iwc" );
        this.storage.setItem( this.NAMESPACE + "iwc", { i: 1, a: [] }.toJSON() );
        log.debug('loaded eventID: ' + this.eventID);
        
    },


    eventStorage: function( event ) {
        var eid = parseInt( this.storage.getItem( this.NAMESPACE + "iwc-eid" ) );
        if ( !eid )
            this.eventID = eid = 1;

        if ( this.eventID == eid )
            return;

        log.debug('eventStorage - eventID changed from '+this.eventID+' to '+eid);
        
        this.eventID = eid;

        var val = this.storage.getItem( this.NAMESPACE + "iwc" );
        if ( !val )
            return;

        var save = false;
        
        var v = eval( "(" + val + ")" );
        if ( !v.a ) {
            v.a = [];
            save = true;
        }

        var ms = ( new Date ).getTime();
        var l = v.a.length;
        
        for ( var i = 0; i < l; i++ ) {
            if ( v.a[ i ].f != this.clientID ) {
                if ( !v.a[ i ].t.hasOwnProperty( this.clientID ) 
                    && v.a[ i ].e == eid ) {
                    log.debug( 'eventIWC: eid: ' + eid + ' ' + v.a[ i ].d.toJSON() );
                    this.broadcastToObservers( "eventIWC", this, { data: v.a[ i ].d, client: v.a[ i ].f, eid: eid }, event );
                    v.a[ i ].t[ this.clientID ] = ms;
                    save = true;
                }
            }
        }

        if ( save )
            this.storage.setItem( this.NAMESPACE + "iwc", v.toJSON() );
    },


    send: function( data ) {
        var val = this.storage.getItem( this.NAMESPACE + "iwc" );
        var eid = parseInt( this.storage.getItem( this.NAMESPACE + "iwc-eid" ) );

        var v  = {};
        if ( val )
            v = eval( "(" + val + ")" );

        if ( !v.a )
            v.a = [];
        
        eid++;
        
        log.debug('event '+eid+' sent');
        
        v.a.push({
            f: this.clientID,      /* from     */
            e: eid,                /* event id */
            d: data,               /* data     */
            t: {}                  /* sent to  */
        });
        
        /* storage events are coalesced */
        this.storage.setItem( this.NAMESPACE + "iwc", v.toJSON() );
        this.storage.setItem( this.NAMESPACE + "iwc-eid", this.eventID = eid );

        if ( this.timer )
            this.timer.reset( this.CLEANUP_TIMER );
        else
            this.timer = new Timer( this.getIndirectMethod( "cleanupEvents" ), this.CLEANUP_TIMER, 1 );
    },


    cleanupEvents: function() {
        this.timer = null;
        var eid = parseInt( this.storage.getItem( this.NAMESPACE + "iwc-eid" ) );
        if ( !eid )
            this.eventID = eid = 1;

        var val = this.storage.getItem( this.NAMESPACE + "iwc" );
        if ( !val )
            return;

        var save = false;
        
        var v = eval( "(" + val + ")" );
        if ( !v.a ) {
            v.a = [];
            save = true;
        }

        var l = v.a.length;
        for ( var i = 0; i < l; i++ ) {
            /* owner of events remove their own when they expire (s) */
            if ( v.a[ i ].f == this.clientID && v.a[ i ].e <= eid ) {
                log.debug( 'removing event ' + v.a[ i ].e);
                v.a.splice( i, 1 );
                i--; l--;
                save = true;
            }
        }

        if ( save )
            this.storage.setItem( this.NAMESPACE + "iwc", v.toJSON() );
    }

});


/* I can't quite subclass the Storage object yet */
WhatWGStorage = new Class( Object, {

    init: function( domain, callback ) {
        if ( !domain )
            throw "domain needed";
        if ( !callback )
            throw "domain needed";
        this.domain = domain;
        this.storage = globalStorage[ domain ];
        DOM.addEventListener( document, "storage", callback );
    },


    getItem: function() {
        return this.storage.getItem.apply( this.storage, arguments );
    },
    
   
    setItem: function() {
        return this.storage.setItem.apply( this.storage, arguments );
    }

});


/* IE 5.1+ */
IEPersistentStorage = new Class( Object, {
    

    init: function( domain, callback ) {
        if ( !domain )
            throw "domain needed";
        if ( !callback )
            throw "domain needed";

        this.domain = domain;
        this.callback = callback;

        this.items = {};
        this.itemlist = [];

        this.timer = new Timer( this.getIndirectMethod( "checkValue" ), 150 );
    },


    destroy: function() {
        this.callback = null;
        this.items = null;
        this.itemlist.length = 0;
    },



    checkValue: function() {
        if ( !this.itemlist.length )
            return;
        var l = this.itemlist.length;
        for ( var i = 0; i < l; i++ ) {
            var key = this.itemlist[ i ];
            var storage = this.items[ key ];
            var va = storage.getAttribute( key );
            try {
                storage.load( "oXMLStore" );
            } catch( e ) {
                if ( e.message )
                    e = e.message;
                log.error( e );
            };
            var vv = storage.getAttribute( key );
            if ( this.callback && va != vv )
                this.callback( { domain: this.domain, key: key } );
        }
    },


    getItem: function( key ) {
        var storage = this.getStorage( key, true );
        if ( !storage )
            return null;
        while( 1 ) {
            /* IE doesn't lock thread access to storage
             * it just throws an error instead
             */
            try {
                storage.load( "oXMLStore" );
            } catch( e ) {
                if ( e.message )
                    e = e.message;
                log.error( e );
                continue;
            };
            break;
        }
        var v = storage.getAttribute( key );
        return v;
    },


    setItem: function( key, value ) {
        var storage = this.getStorage( key, true );
        if ( !storage )
            return false;
        storage.setAttribute( key, value );
        while( 1 ) {
            /* IE doesn't lock thread access to storage
             * it just throws an error instead
             */
            try {
                storage.save( "oXMLStore" );
            } catch( e ) {
                if ( e.message )
                    e = e.message;
                log.error( e );
                continue;
            };
            break;
        }
        if ( this.callback )
            this.callback( { domain: this.domain, key: key } );
        return true;
    },


    getStorage: function( key, create ) {
        var storage;
        if ( this.items.hasOwnProperty( key ) )
            storage = this.items[ key ];
        else {
            if ( !create )
                return null;
            storage = document.createElement( "input" );
            storage.setAttribute( "type", "hidden" );
            storage.addBehavior ( "#default#userData" );
            storage.className = "userData";
            storage.setAttribute( "id", "storage-" + key );
            document.body.appendChild( storage );
            this.items[ key ] = storage;
            this.itemlist.push( key );
        }
        return storage;
    }

});


