var Overlay = new Class({

	initialize: function(options){
		this.options    = $extend({ closeLink: true }, options || {});
	    this.overlayMask = new Element('div', { 'id' : 'overlay-mask' }).setStyles({'background-color' : '#000', 
	    																			'width' : '100%', 
	    																			'height' : '100%', 
	    																			'position' : 'fixed', 
	    																			'top' : '0', 
	    																			'left' : '0',
	    																			'z-index' : '100'
	    																			}).fade('hide');
		compatibleOverlay = Browser.Engine.trident4 || (this.overlayMask.currentStyle && (this.overlayMask.currentStyle.position != "fixed"));																			
		if (compatibleOverlay) this.overlayMask.setStyles({'width': window.getScrollSize().x, 'height': window.getScrollSize().y, 'position': 'absolute'});
		
		var closeAction = function() { this.hide(); return false; }
		var boundHide = closeAction.bind(this);
	
		this.overlayMask.addEvent('click', boundHide);
		
		
		this.overlayWindow = new Element('div', { 'id' : 'overlay' }).fade('hide');
		this.overlayWindow.setStyles({'margin' : '5em auto'});
		this.contents = new Element('div', { 'id' : 'contents' }).inject(this.overlayWindow);
		
		if (this.options.closeLink) {
			this.closeButton = new Element('p', { 'id' : 'close' }).inject(this.overlayWindow);
			this.closeLink = new Element('a', { 'text' : 'Close this window' }).setStyle('cursor', 'pointer').inject(this.closeButton);
			this.closeLink.addEvent('mouseup', boundHide);
		}
			
		this.overlayMask.set('tween', {duration: '400'});
	    this.overlayWindow.set('tween', {duration: '400'});
		
		$(document.body).adopt(this.overlayWindow, this.overlayMask);		
	},	

	show: function(content, clone){
		if (clone == null) clone = true;
	    this.injectContent(content, clone);
	
		this.overlayWindow.setStyles({'top' : window.getScrollTop() + 20 });	
		
		this.fadeInOverlayMask.bind(this).delay('0');
	    this.fadeInOverlayWindow.bind(this).delay('200');
	},
	
	replace: function(content, clone){			
    	this.fadeOutOverlayWindow();
    	this.injectContent(content, clone).bind(this).delay('400');
	    this.fadeInOverlayWindow().bind(this).delay('400');
	},
	
	hide: function(){
	    this.overlayMask.fade('out');
	    this.overlayWindow.fade('out');
	},
	
	injectContent: function(content, clone){	
	   	this.contents.empty();
		if (clone) {
	    	content.clone().inject(this.contents);
	    } else {
	    	content.inject(this.contents);
	    }
	},
		
	fadeInOverlayMask: function(){
		this.overlayMask.fade(0, 0.8);
	},
	
	fadeOutOverlayMask: function(){
		this.overlayMask.fade('out');
	},
	
	fadeInOverlayWindow: function(){		
		this.overlayWindow.fade(0,1); 
	},
	
	fadeOutOverlayWindow: function(){
	    this.overlayWindow.fade('out');
	}
});
