﻿(function($){

	// Save the image dimensions
	$.fn.saveSize = function()
	{
		return this.each(function(){
			var j = $(this)
			if (this.originalWidth == undefined)
			{
				this.originalWidth = j.width()
				this.originalHeight = j.height()
				this.aspectRatio = this.originalWidth / this.originalHeight
			}
		})
	}


	// Resize the image to exactly fit the given size and maintain the aspect ratio
	// Note the images is never resized larger than its original size.
	$.fn.fitToSize = function(maxWidth, maxHeight)
	{
		this.saveSize()
		return this.each(function(){
			if( maxWidth < 10 )
				maxWidth = 10
			else if ( maxWidth > this.originalWidth )
				maxWidth = this.originalWidth
			
			if( maxHeight < 10 )
				maxHeight = 10
			else if ( maxHeight > this.originalHeight )
				maxHeight = this.originalHeight

			var targetRatio = maxWidth / maxHeight
			if (this.aspectRatio > targetRatio)
				maxHeight = Math.floor(maxWidth / this.aspectRatio)
			else
				maxWidth =  Math.floor(maxHeight * this.aspectRatio)

			$(this).width(maxWidth)
						 .height(maxHeight)
		})
	}

	// Fit the image into the centre of the given rectangle
	$.fn.centre = function(left, top, width, height)
	{
		return this.each(function(){
			var j = $(this)
			var leftMargin = Math.floor((width - j.width()) / 2)
			var topMargin = Math.floor((height - j.height()) / 2)
			j.css({left: left + leftMargin,
						 top : top + topMargin})
		})
	}

})(jQuery)
