var Lightbox = Class.create({  //- v0.4
    initialize: function(conf) {
        Object.extend(this, conf || {});
        if(this.id && $(this.id)) {
            this.element = $(this.id);
        }

        var ua = navigator.userAgent.toLowerCase(),
        check = function(r){
            return r.test(ua);
        };

        this.isOpera =    check(/opera/);
        this.isIE =      !this.isOpera && check(/msie/);
        this.isTrident =  this.isIE && check(/trident\//);
        this.isIE8asIE7 = this.isIE && this.isTrident  && check(/msie 7/);
        this.isIE7 =      this.isIE && !this.isTrident && check(/msie 7/);
        this.isIE6 =      this.isIE && check(/msie 6/);

        Lightbox.register(this);


    },
    id:'',
    width: 400,
    height: 400,
    cb: Prototype.emptyFunction,
    maskColour:'#000000',
    maskOpacity: 0.5,
    fadeDuration: 0.5,
    url: null,
    refreshImage:'/images/icon_refresh.png',
    closeImage:'/images/icon_close.png',
    closeImageStyles:{},
    
    show: function() {
        if(this.url) {
            this.showUrl(this.url);
        }
        else if(this.element) {
            if(!this.element) {
                this.render();
            }
            this.setPosition();
            this.activate();
        }
    },

    /**
     * 
     *  @example lightbox.showUrl('/site_includes/newsletter-signup.php');
     *  @param url The URL to load into the lightbox
     */
    showUrl: function(url) {
        if(!this.element) {
            this.render();
        }
        this.setPosition();
        this.load(url, this.activate);
    },
    load: function(url, callback, scope) {
        this.lastUrl = url;
        new Ajax.Updater(this.elementInner, url, {
            evalScripts: true,
            method: 'GET',
            onComplete: typeof callback == "function" ? callback.bind(scope || this) : Prototype.emptyFunction
        });
    },
    reload: function() {
        if(this.lastUrl) {
            this.load(this.lastUrl, function() {
                this.cb();
            });
        }
    },
    activate: function() {
        this.maskPage(function() {
            this.element.appear({
                duration: this.fadeDuration,
                afterFinish: function() {
                    this.cb();
//                    this.elementInner.setStyle({
//                        overflow:'auto'
//                    });
                    if(this.isTrident || this.isIE8 || this.isIE8asIE7 ) { //- but not real IE7 - shadow slows it down badly
                        this.renderShadow();
                    }
                    if(this.elementShadow) {
                        this.elementShadow.show();
                        this.setPosition();
                    }
//                    Event.observe(window, 'scroll', function(){
//                        this.setPosition();
//                    }.bind(this));
                }.bind(this)
            });
        }.bind(this));
    },
    hide: function(){
        if(this.element) {
            this.elementInner.setStyle({
                overflow:'auto'
            });
            this.element.fade({
                duration: this.fadeDuration,
                afterFinish: function() {
                    this.removeMask();
                    if(this.elementClose) this.elementClose.remove();
                    if(this.elementReload) this.elementReload.remove();
                    if(this.elementShadow) this.elementShadow.remove();
                    if(this.element) this.element.remove();
                    this.element = this.elementShadow = this.elementInner = this.elementClose = this.elementReload = null;
                }.bind(this)
            });
            if(this.elementShadow) {
                this.elementShadow.hide();
            }
        }
        else {
            this.removeMask();
        }

//        Event.stopObserving(window, 'scroll');

    },
    visible: function() {
        return this.element && this.element.visible();
    },
    maskPage: function(callback) {
            
        var mask = $(this.id + '-mask');

        if (!mask) {
            var tmp = $(window.opera && parseFloat(window.opera.version()) < 9.5 ? document.documentElement : document.body);

            var padding = parseInt(tmp.getStyle('padding-bottom')) + parseInt(tmp.getStyle('padding-top'));

            mask = new Element('DIV');
            mask.id = this.id + '-mask';
            mask.setStyle({
                top:  0,
                left: 0,
                width:  tmp.clientWidth + 'px',
                height: (tmp.clientHeight+padding) + 'px',
                display:'none',
                position:'absolute',
                backgroundColor:this.maskColour,
                zIndex:1000
            });

            $(document.body).insert(mask);

        }

        mask.appear({
            from:0,
            duration: this.fadeDuration,
            to:this.maskOpacity,
            afterFinish: callback || Prototype.emptyFunction
        });


    },
    removeMask: function() {
        var mask = $(this.id + '-mask');
        if (mask) {
            mask.fade({
                from: this.maskOpacity,
                duration: 0.5,
                to: 0,
                afterFinish: function() {
                    mask.remove();
                }
            });
        }
    },
    setPosition: function() {
//        var viewport_width = document.viewport.getWidth();
        var viewport_height = document.viewport.getHeight();
        var vpscroll_top = this.element.getStyle('position') == 'fixed' ? 0 : document.viewport.getScrollOffsets()['top'];
        var new_top = ((viewport_height - this.height) / 2) + vpscroll_top;

        this.element.setStyle({
            marginLeft: '-' + Math.round(this.width / 2) + 'px',
            left: '50%',
            top: new_top + 'px'
        });
        if(this.elementShadow) {
            this.elementShadow.setStyle({
                marginLeft: '-' + (Math.round((this.width-4) / 2)+(this.shadowWidth)) + 'px',
                left: '50%',
                top: Math.round(new_top-(4)) + 'px'
            });
        }

    },
    render: function() {

        this.element = new Element('DIV',{
            id: this.id || ''
        });
        this.id = this.element.identify();

        this.element.addClassName('lightbox');

        this.element.setStyle({
            position: this.isIE6 ? 'absolute' : 'fixed',
            display: 'none',
            zIndex: 2000,
            backgroundColor:'#ffffff',
            height: this.height + 'px'
        });

        this.elementInner = new Element('DIV', {
            id: this.id+'-inner'
        });
        this.elementInner.setStyle({
            position:'relative',
            overflow: 'hidden', //Prototype.Browser.Opera ? 'hidden' : 'auto',
            width: this.width + 'px',
            height: this.height + 'px'
        });
        this.elementInner.addClassName('lightbox-inner');

        this.element.insert(this.elementInner);
		
		//create top and bottom gradients to lightbox
		
		//top
		
		this.elementInnerTop = new Element('DIV', {
            id: this.id+'-innerTop'
        });
		this.elementInnerTop.setStyle({
            position:'absolute',
            //overflow: 'hidden', //Prototype.Browser.Opera ? 'hidden' : 'auto',
            top:'0',
			left:'0',
			height:'73px',
			width:'100%',
			backgroundImage:'url(../images/lightbox_gradient_top.jpg)',
			zIndex:'-1000'
        });
		
		//bottom
		
		this.elementInnerBottom = new Element('DIV', {
            id: this.id+'-innerBottom'
        });
		this.elementInnerBottom.setStyle({
            position:'absolute',
            //overflow: 'hidden', //Prototype.Browser.Opera ? 'hidden' : 'auto',
            bottom:'0',
			left:'0',
			height:'51px',
			width:'100%',
			backgroundImage:'url(../images/lightbox_gradient_bottom.jpg)',
			zIndex:'-1000'
        });
		
		this.element.insert(this.elementInnerTop);
		this.element.insert(this.elementInnerBottom);

        this.elementClose = new Element('DIV', {
            id: this.id + '-close',
            title: 'Close'
        });

        var closeStyles = {
            position: 'absolute',
            display: 'block',
            top: '-12px',
            right: '-12px',
            width: '33px',
            height: '34px',
            zIndex: 2100,
            cursor:'pointer',
            background:'transparent url('+this.closeImage+') no-repeat scroll 0 0'
        }
        Object.extend(closeStyles, this.closeImageStyles);


        this.elementClose.setStyle(closeStyles);
        this.elementClose.observe('click', function() {
            this.hide();
        }.bind(this));

        this.elementClose.update('&nbsp;');
        this.element.insert(this.elementClose);


        this.elementReload = new Element('DIV', {
            id: this.id + '-reload',
            title: 'Reload'
        });
        var reloadStyles = {
            position: 'absolute',
            display: 'block',
            top: '0',
            right: '40px',
            width: '16px',
            height: '16px',
            zIndex: 2100,
            cursor:'pointer',
            background:'transparent url('+this.refreshImage+') no-repeat scroll 0 0'
        }
        Object.extend(reloadStyles, this.closeImageStyles);

        reloadStyles.right = '25px';

        this.elementReload.setStyle(reloadStyles);
        this.elementReload.observe('click', function() {
            this.reload();
        }.bind(this));

        this.elementReload.update('&nbsp;');
        this.element.insert(this.elementReload);

        $(document.body).insert(this.element);
    },
    shadowWidth: 6,
    renderShadow: function() {

        if(this.elementShadow) return;

        //<div class="x-shadow" id="'+this.id+'-shadow" style="">

        var w = this.width + 1;
        var h = this.height + 1;

        var width = w + (this.shadowWidth * 2);
        var height = h + (this.shadowWidth * 2);

        this.elementShadow = new Element('div', {
            'class': 'x-shadow'
        });
        this.elementShadow.setStyle({
            position: this.isIE6 ? 'absolute' : 'fixed',
            zIndex: '1000',
            left: '10px',
            top: '10px',
            width: width+'px',
            height: height+'px',
            display: 'none'
        });
        
        var html = '<div class="xst">'
                 + '    <div class="xstl"></div><div class="xstc" style="width: '+w+'px;"></div><div class="xstr"></div>'
                 + '</div>'
                 + '<div class="xsc" style="height: '+h+'px;">'
                 + '    <div class="xsml"></div><div class="xsmc" style="width: '+w+'px;"></div><div class="xsmr"></div>'
                 + '</div>'
                 + '<div class="xsb">'
                 + '    <div class="xsbl"></div><div class="xsbc" style="width: '+w+'px;"></div><div class="xsbr"></div>'
                 + '</div>';

         this.elementShadow.update(html);

         $(document.body).insert(this.elementShadow);
    }
});


Lightbox.boxes = [];
Lightbox.register = function(lb) {
    Lightbox.boxes.push(lb);
}
Lightbox.close = function() {
    Lightbox.boxes.each(function(lb) {
        if(lb.visible()) {
            lb.hide();
        }
    });
}