/* jquery.imagefit 
 *
 * Version 0.2 by Oliver Boermans <http://www.ollicle.com/eg/jquery/imagefit/>
 *
 * Extends jQuery <http://jquery.com>
 *
 */
(function($) {
	$.fn.imagefit = function(options) {
		var fit = {
			all : function(imgs){
				imgs.each(function(){
					fit.one(this);
					})
				},
			one : function(img){
				$(img)
					.width('100%').each(function()
					{
						if($(this).width() > $(this).attr('startwidth'))
						{
							// This is basically a hack for IE6/7. It doesn't support the CSS max-width.
							// console.log($(this))
							var alto = $(this).attr('startheight')+"px"
							var ancho = $(this).attr('startwidth')+"px"
							$(this).width(ancho).height(alto)
							// console.log('alto: '+alto+' - ancho: '+ancho)
							// console.log($(this).width()+' - '+$(this).attr('startwidth'))														
						}
						else
						{
							$(this).height(Math.round(
								$(this).attr('startheight')*($(this).width()/$(this).attr('startwidth')))
							);
						}
					})
				}
		};
		
		this.each(function(){
				var container = this;
				
				// store list of contained images (excluding those in tables)
				var imgs = $('img', container).not($("table img"));
				
				// store initial dimensions on each image 
				imgs.each(function(){
					// console.log('img');
					// console.log($(this).width());
					$(this).attr('startwidth', $(this).width())
						.attr('startheight', $(this).height())
						// Unfortunately not supported by IE
						// .css('max-width', $(this).attr('startwidth')+"px");
				
					// console.log($(this).attr('startwidth'));
					// console.log($(this).css('max-width'));
					fit.one(this);
				});
				// Re-adjust when window width is changed
				$(window).bind('resize', function(){
					fit.all(imgs);
				});
			});
		return this;
	};
})(jQuery);