// Scale an image (within the browser) to fit within its
// containing element, either by cropping or by fitting
// the entire image within the container.
function scaleImageToContainer(img, mode) {
	// default mode is to fit the entire images within the frame
	if (mode != 'crop') {
		mode = 'fit';
	}

	// get dimensions of the box we're trying to fill
	// note: use "img_container" instead of "container" because IE chokes on the latter
	img_container = img.parentNode;
	if (!(target_width = img_container.offsetWidth) || !(target_height = img_container.offsetHeight)) {
		return;
	}
	img_container.style.overflow = 'hidden';

	// get the original image dimensions
	unscaled = new Image();
	unscaled.src = img.src;

	// set initial height and width
	var w = unscaled.width;
	var h = unscaled.height;
	
	// fit horizontally
	if(w>target_width){
		h = Math.round((target_width/w)*h);
		w = target_width;
	}
	// fit or crop vertically
	if (mode == 'fit' && h>target_height){
		w = Math.round((target_height/h)*w);
		h = target_height;
	}
	else if (mode == 'crop' && h<target_height){
		w = Math.round((target_height/h)*w);
		h = target_height;
	}

	// never size bigger than the original
	if (w > unscaled.width || h > unscaled.height) {
		w = unscaled.width;
		h = unscaled.height;
	}

	// apply scaled width and height to image object
	img.width = w;
	img.style.width = w+'px';
	img.height = h;
	img.style.height = h+'px';

	// center the image within the container
	if (!img.style.position) {
		img.style.position = 'relative';
	}
	img.style.top = Math.round((target_height-h)/2) + 'px';
	img.style.left = Math.round((target_width-w)/2) + 'px';
}
