// kingdee JoelLeung
//add valign parameter(top, middle(default), bottom)  --emil edit
function ImageAdjustor(img, w, h, valign) {
	
	YAHOO.util.Event.onContentReady(img, function() {
		if (img.constructor == String) this.img = document.getElementById(img);
		else this.img = img;
		this.w = w;
		this.h = h;
		this.valign = valign;
		this.init();
	}, this, this);
	
	this.retryCount = 80;
	this.testInterval = 100;
	
}

ImageAdjustor.prototype = {

	init: function() {
	
		this.imgWidth = $(this.img).width();
		this.imgHeight = $(this.img).height();
		//alert(this.imgWidth);
		//alert(this.imgHeight);
		
		var adjustor = this;
		
		var tag = ((this.imgWidth == 0 && this.imgHeight == 0) || 
					(this.imgWidth == 28 && this.imgHeight == 30))
		          && this.retryCount > 0;
		
		while (tag) {
			//alert(1);
			this.retryCount--;
			setTimeout(function(){
				adjustor.init();
			}, this.testInterval);
			//alert(this.imgHeight);
			return;
		}
		
		this.adjustImage();	
	},
	
	adjustImage: function() {
		this._computeResult();
		$(this.img).width(this.resultWidth).height(this.resultHeight);
		//alert(this.h);
		//alert(this.resultHeight);
		if (this.valign == "top") {
			//don't set margin-top
		} else if (this.valign == "middle") {
			$(this.img).css("margin-top", this._computeMarginTop());
		} else if (this.valign == "bottom") {
			$(this.img).css("margin-top", this._computeMarginTop2());
		} else {
			$(this.img).css("margin-top", this._computeMarginTop());
		}
	},
	
	_computeMarginTop: function() {
		var parentHeight = $(this.img).parent().height();
		if (parentHeight > this.resultHeight) return (parentHeight - this.resultHeight) / 2;
		else return 0;
	},
	
	_computeMarginTop2: function() {
		var parentHeight = $(this.img).parent().height();
		if (parentHeight > this.resultHeight) return (parentHeight - this.resultHeight) + 1;
		else return 0;
	},
	
	_computeResult: function() {
		this.resultWidth = this.imgWidth;
		this.resultHeight = this.imgHeight;
		var widthScale = this.imgWidth / this.w;
		var heightScale = this.imgHeight / this.h;
		
		if (widthScale > 1 || heightScale > 1) {
			if (widthScale > heightScale) {
				var factor = this.w / this.imgWidth;
				this.resultHeight = this.imgHeight * factor;
				this.resultWidth = this.w;
			} else {
				var factor = this.h / this.imgHeight;
				this.resultWidth = this.imgWidth * factor;
				this.resultHeight = this.h;
			}
		}
	}
	
}