var Loader = new Class({

	Implements:[Options,Events],

	options:{
		minLife:100,
		offset:{
			x:10,
			y:10
		}
	},

	initialize:function() {

		//setup the loader
		this.frame = new Element('div',{
			'class':'loader-frame',
			'styles':{
				'position':'absolute',
				'top':-9999,
				'left':-9999
			}
		}).injectInside(document.body);

		this.content = new Element('div',{
			'class':'loader-content'
		}).injectInside(this.getFrame());

		//hide it anyways
		this.hide();

		var adjust = function(event) {
			event = event || {};
			event.page = event.page || {};
			var x = event.page.x || null;
			var y = event.page.y || null;
			this.position(x,y);
		}.bind(this);

		this.mouse = {};
		document.addEvent('mousemove',adjust);
		window.addEvent('scroll',adjust);
	},

	hasMinLifePassed:function() {
		return this.isShowing() && this.minLifePassed;
	},

	position:function(x,y) {

		if(x && y) {
			this.mouse.x = x;
			this.mouse.y = y;
		}
		else {
			x = this.mouse.x;
			y = this.mouse.y;
		}

		//check visible
		if(!this.isShowing()) return;

		//get the offsets
		var offset = this.options.offset;
		x += offset.x || 0;
		y += offset.y || 0;

		this.getFrame().setStyles({
			'left':x,
			'top':y
		});

	},

	getFrame:function() {
		return this.frame;
	},

	isShowing:function(delay) {
		return this.showing;
	},

	show:function(delay) {
		this.minLifePassed = false;
		this.showing = true;
		this.getFrame().setStyles({
			'display':'block'
		});

		this.position();
		if(delay&&delay>0) this.hide(delay);
	},

	hide:function(delay) {

		var H = function() {
			this.showing = false;
			this.minFile = null;
			this.minLifePassed = false;
			this.getFrame().setStyles({
				'display':'none',
				'top':-9999,
				'left':-9999,
				'opacity':1,
				'visibility':'visible'
			});
		}.bind(this);

		var F = function() {
			if(delay && delay>0) {
				H.delay(delay,this);
			}
			else {
				H();	
			}
		};

		if(this.hasMinLifePassed()) {
			F();	
		}
		else {
			this.minFire = F;
		}
	},

	setOpacity:function(opacity) {
		this.getFrame().setOpacity(opacity);
	},

	fadeIn:function(delay) {

		var opacity = this.options.opacity;
		this.setOpacity(0);
		this.show();

		//fade in
		var self = this;
		new Fx.Tween(this.getFrame()).start('opacity',1).chain(function() {
			(function() {
				this.minLifePassed = true;
				if(this.minFire) {
					this.minFire();	
				}
			}).delay(this.options.minLife,self);
		}.bind(self));

		if(delay&&delay>0) this.hide(delay);
	},

	fadeOut:function() {
		if(this.isShowing()) {
			
			var F = function() {
				new Fx.Tween(this.getFrame()).start('opacity',0).chain(this.hide.pass([0],this));
			}.bind(this);
			
			if(this.hasMinLifePassed()) {
				F();	
			}
			else {
				this.minFire = F;
			}
		}
	}
});

Loader = new Loader;
