var ScaledBackground = new Class({
	
	Implements: [Options],
	
	options: {
		gravity: 'c',
		x: 0,
		y: 0
	},
	
	gravity: {
		nw: [0, 0],
		n : [0.5, 0],
		ne: [1, 0],
		e : [1, 0.5],
		se: [1, 1],
		s : [0.5, 1],
		sw: [0, 1],
		w : [0, 0.5],
		c : [0.5, 0.5]
	},
	
	initialize: function(object, options) {
		this.object = $(object);
		var size = this.object.getParent().measure(function() {
			return this.object.getSize();
		}.bind(this));
		this.ratio = size.x / size.y;
		this.setOptions(options);
		window.addEvent('resize', this.resize.bind(this));
	},
	
	resize: function() {
		this.object.setStyles(this.calculate());
	},
	
	calculate: function() {
		var size = window.getSize(), result = {};
		var w = size.x, h = size.y;
		result.width = (w/h <= this.ratio) ? h * this.ratio : w;
		result.height = (w/h <= this.ratio) ? h : w / this.ratio;
		return $extend(result, this.gravitate(w - result.width, h - result.height));
	},
	
	gravitate: function(dx, dy) {
		var gravity = $type(this.options.gravity) == 'string' ? this.gravity[this.options.gravity] : this.options.gravity;
		return {
			left: (dx * gravity[0] + this.options.x).limit(dx, 0),
			top : (dy * gravity[1] + this.options.y).limit(dy, 0)
		};
	}
	
});

