﻿/// <reference path='~/jQuery/jQuery-vsdoc.js' />
(function($)
{
	// Note the image is never resized larger than its original size.
	$.fn.fitToSize = function(maxWidth, maxHeight, options)
	{
		var settings = $.extend({
			justify: 'none',
			top: 0
		}, options || {})
		/// <summary>Resize the image to fit within the given size and maintain the aspect ratio</summary>
		return this.each(function()
		{
			var width = maxWidth
			if (width > this.originalWidth)
				width = this.originalWidth

			var height = maxHeight
			if (height > this.originalHeight)
				height = this.originalHeight

			var targetRatio = width / height
			if (this.aspectRatio > targetRatio)
				height = Math.floor(width / this.aspectRatio)
			else
				width = Math.floor(height * this.aspectRatio)

			$(this).width(width)
						 .height(height)
			if (settings.justify == 'left')
			{
				var left = maxWidth - width
				$(this).css({ opacity: 1.0,
											left: left,
											top: settings.top
									 })
			}
		})
	}

	$.fn.centre = function(left, top, width, height)
	{
		/// <summary>Fit the image into the centre of the given rectangle</summary>
		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)

