var Loader = new Class({

	options: {
		width : 0,
		height : 0,
		image : '',
		background : '#000',
		opacity: 1,
		delay: 50,
		zIndex: 1
	},

	initialize: function(options) {
		this.setOptions(options);
		this.done = false;
		this.load = false;
		this.image = new Asset.image(this.options.image, {'alt': ''});
		window.addEvents({
			'domready': this.delay.bind(this),
			'load': this.stop.bind(this)
		});
	},

	delay: function() {
		this.start.delay(this.options.delay, this);
	},

	start: function() {	
		if(!this.done) {
			this.load = true;
			var body = $(document.body);
			this.overflow = body.getStyle('overflow');
			body.setStyle('overflow', 'hidden');
			
			this.overlay = new Element('div').setStyles({
				'margin': 0,
				'padding': 0,
				'border': 0,
				'position': 'absolute',
				'width': '100%',
				'height': window.getHeight(),
				'background': this.options.background,
				'z-index': this.options.zIndex,
				'opacity': this.options.opacity
			}).injectTop(body);
						
			this.image.setStyles({
				'margin': 0,
				'padding': 0,
				'border': 0,
				'position' : 'absolute',
				'top' : (window.getHeight() - this.options.height) / 2,
				'left' : (window.getWidth() - this.options.width) / 2,
				'z-index': this.options.zIndex + 1,
				'width': this.options.width,
				'height': this.options.height
			}).injectTop(body);
			
			window.addEvent('resize', this.set.bind(this));
		}
	},
	
	set: function() {
		this.overlay.setStyle('height', window.getHeight());
		this.image.setStyles({'top' : (window.getHeight() - this.options.height) / 2,'left' : (window.getWidth() - this.options.width) / 2});
	},

	stop: function() {
		this.done = true;
		if (this.load) {
			this.image.setOpacity(0).setStyle('display', 'none');
			var overflow = this.overflow;
			new Fx.Style(this.overlay, 'opacity', this.options).start(0).chain(function() {
				this.element.setStyle('display', 'none');
				$(document.body).setStyle('overflow', overflow);
			});	
		}
		window.fireEvent('loadReady');
	}

});

Loader.implement(new Options);