// check dependencies
if (!Prototype.Version) {
    throw('bbb.js requires prototype.js');
}

BBB = Class.create();
BBB.prototype = {
    hash: '',

    frame: null,
    config: {},
    defaults: {
        callback: null,
        frame: {
            src: '/static/blank.html',
            id: 'pagerflame'
        }
    },

    initialize: function(config) {
        // current version of Safari has strange bugs and doesn't work, so ignore it
        // if (navigator.userAgent.match(/Safari/)) return;

        this.config = config || {};
        if (!this.config['frame']) this.config['frame'] = {};

        if (location.hash) {
            this.hash = location.hash;
        }

        Event.observe( window, 'load', this.onLoad.bindAsEventListener(this) );
    },


    watch: function() {
        if (this.hash != location.hash) {
            this.config.callback( (this.hash = location.hash).replace(/^#/, '') );
        }
    },

    change: function(hash) {
        if (this.frame) {
            this.frame.src = this.frame.src.replace(/(\?.*|$)/, '?'+hash);
        }
        else {
            location.hash = hash;
        }

        return false;
    },

    onLoad: function(e) {
        // IE requires iframe hack (Safari too)
        if (navigator.userAgent.match(/MSIE/) || (navigator.userAgent.match(/Safari/))) {
            (function(){
                 var iframe = document.createElement('iframe');
                 iframe.src = (this.config['frame']['src'] || this.defaults.frame.src) + '?' + this.hash;
                 iframe.id  = this.config['frame']['id']  || this.defaults.frame.id;
                 iframe.style.border = 'none';
                 iframe.style.padding = '0';
                 iframe.style.margin  = '0';
                 iframe.style.width   = '0px';
                 iframe.style.height  = '0px';

                 document.body.appendChild( this.frame = iframe );
            }).bind(this)();
        }

        // restore page
        if (location.hash) {
            this.config.callback( (this.hash = location.hash).replace(/^#/, '') );
        }

        // start watcher
        new PeriodicalExecuter( this.watch.bind(this), 0.1 );
    },

    dummy: null
};
