/*
 * hyCMS
 * Copyright(C)2008 by Friedrich Gräter
 * Published under the terms of the Lesser GNU General Public License v2
 *
 * WidgetKit backend: Button widget
 *
 * Please Note: This module has to be clean from all dependencies to predicateJS!
 *
 *				Also this module requires "widget-kit.css" to be
 *				embedded to the parent site for styling the widgets.
 *
 */

/*
 * wk_createScaledImage(id, url, minHeight, minWidth, maxHeight, maxWidth[, relatedDocument])
 *
 * Creates an image view that shows the given image at "url". The method
 * tries fit the given image to the given size constraints by keeping the aspect ratio.
 * If a constraint parameter is set to -1, it will be ignored.
 *
 * I triggers the following events:
 *
 *	imageLoaded						The image is completly loaded and scaled
 *	resized							The view was resized
 *
 */
function wk_createScaledImage(id, url, maxHeight, maxWidth, relatedDocument)
{
	if (relatedDocument == null)
		relatedDocument = document;

	var view = relatedDocument.createElement("img");
	view.wk_type = "scaledImage";
		
	view.id = id;
	view.className = "wk_scaledImage";
	
	// Events
	wk_declareEvents(view, "resized");
	wk_declareEvents(view, "imageLoaded");	

	// Load image
	view.src = 	url;
	view.style.display = "none";
	
	// Wait until image is loaded
	var win = view.ownerDocument.defaultView;
	if (win == null) win = window;

	var interval = win.setInterval(__testLoaded, 100);
	
	
	function __testLoaded()
	{
		var height, width, scaleH, scaleW, doScale;

		if (!view.complete) return;

		view.style.display = "";
		win.clearInterval(interval);
		
		height = view.height;
		width = view.width;
		
		if ((maxHeight != -1) || (maxWidth != -1)) {
			scaleH = maxHeight / height;
			scaleW = maxWidth / width;
		
			if ((scaleH < scaleW) && (maxHeight > -1))
				doScale = scaleH;
			else
				doScale = scaleW;

			if (doScale < 1) {
				height = height * doScale;
				width = width * doScale
			}
	
			view.style.height = height + "px";	
			view.style.width = width + "px";			

			if (height < maxHeight)
				view.style.marginTop = ((maxHeight - height) / 2) + "px"
		}

		view.style.display = "";

		wk_triggerEvent(view, "resized");
		wk_triggerEvent(view, "imageLoaded");
	}

	return view;
}


