// Dependências: hooks.js e util.js;
//
// Carrega uma imagem e restringe o seu tamanho, antes de a colocar numa determinada <img>.
// NOTA: Esta classe poderia ser integrada com o 'Miup'.
//

derive (SizedImage, Object)
function SizedImage (img, optMaxW, optMaxH) {	img && this.init (img, optMaxW, optMaxH)	}

// Inicializar.
proto.init = function (img, optMaxW, optMaxH) {
	this.img = img.substr ? elm (img) : img
	this.optMaxW = optMaxW
	this.optMaxH = optMaxH
	this.loader = new Image
	this.w = this.h = 0
}

// Carrega a imagem em 'src'.
proto.load = function (src) {
	var self = this, o = this.loader, optMaxW = self.optMaxW, optMaxH = self.optMaxH
	// Carregar.
	o.onload = function () {
		var o = self.loader, w = this.w = this.width, h = this.h = this.height
		o.onload = null
		// Limitar a largura.
		if (w > optMaxW && optMaxW) {
			h = Math.ceil (this.height * optMaxW / w)
			w = optMaxW
		}
		// Limitar a altura.
		if (h > optMaxH && optMaxH) {
			h = optMaxH
			w = Math.ceil (w * optMaxH / h)
		}
		self.setImage (this.src, w, h, optMaxW, optMaxH)
		runHook (self.onLoad, self)
	}
	// Tratar erros.
	o.onerror = function () {
		var st = self.img.style
		self.img.src = KNoImgURL
		optMaxW && (st.width = optMaxW + "px")
		optMaxH && (st.height = optMaxH + "px")
		runHook (self.onError, self)
	}

	o.src = src
}

// Coloca 'src' como imagem.
proto.setImage = function (src, w, h, optMaxW, optMaxH) {
	var img = this.img, self = this
	img.style.visibility = "hidden"
	listen (img, "load", init)
	img.src = src
	this.w = w
	this.h = h

	function init () {
		var st = img.style
		st.padding = 0
		st.width = w + "px"
		st.height = h + "px"
		optMaxW && optMaxH && self._centerImg (st, w, h, optMaxW, optMaxH)
		st.visibility = "visible"
		unlisten (img, "load", init)
	}
}

// Fazer com que a imagem ocupe todo o espaço que lhe é devido, alinhando-a à esquerda.
proto._centerImg = function (st, w, h, maxW, maxH) {
	var pw = Math.ceil ((maxW - w) / 2), ph = Math.ceil ((maxH - h) / 2)
	var pt = ph + maxH - (h + ph * 2), pl = pw + maxW - (w + pw * 2)
	if (w + pl + pw != maxW) ++pl
	if (h + pt + ph != maxH) ++pt
	
	st.padding = 0
	st.paddingTop = pt + "px"
	st.paddingRight = pw + "px"
	st.paddingBottom = ph + "px"
	st.paddingLeft = pl + "px"
}
