/**
 * @author ricky
 */
var ImageResizer = new Class({
	Implements : [Options],
	options : {
		width : 50,
		height : 50,
		posX : 0,
		posY : 0
	},
	initialize : function(images, options) {
		if (!$type(images) == 'array' || !images.length) {
			return;
		}
		this.images = images;
		this.setOptions(options);
	},
	append : function() {
		$each(this.images, function(img) {
					var nimg = new Image();
					nimg.src = img.src;
					this._calculate_size(img, {
								'x' : nimg.width,
								'y' : nimg.height
							});
				}, this)
	},
	_calculate_size : function(img, size) {
		var proportion;
		var width = size.x;
		var height = size.y;
		if (size.x > this.options.width) {
			proportion = size.x / this.options.width;
			width = this.options.width;
			height = size.y / proportion;
		}
		if (height > this.options.height) {
			proportion = height / this.options.height;
			height = this.options.height;
			width = width / proportion;
		}
		width = width.round();
		height = height.round();
		if (width > this.options.width) {
			--width;
		}
		if (height > this.options.height) {
			--height;
		}
		this._calculate_position(img, {
					'x' : width,
					'y' : height
				});
	},
	_calculate_position : function(img, size) {
		if (size.x < this.options.width && (this.options.width - size.x) > 1) {
			this.options.posX = ((this.options.width - size.x) / 2).round();
		}
		if (size.y < this.options.height && (this.options.height - size.y) > 1) {
			this.options.posY = ((this.options.height - size.y) / 2).round();
		}
		this._place_canvas(img, size);
		this.options.posY = 0;
		this.options.posX = 0;
	},
	_place_canvas : function(img, size) {
		var canvas_tag = new Canvas({
					width : this.options.width,
					height : this.options.height
				});
		canvas_tag.replaces(img);
		var ctx = canvas_tag.getContext('2d');
		ctx
				.drawImage(img, this.options.posX, this.options.posY, size.x,
						size.y);
	}
});
