/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @link www.scorpix.ru
 * @version 0.1.4
 * @date 2010-03-01
 * @requires jQuery
 * @requires jCommon.support, jCommon.attrSuffix
 * @requires photoSizer
 */
var richPictures;

$(function() {
	richPictures = (function() {

		var
			minWidth = 120,
			maxWidth = 240,
			prefix = 'shape_';

		var
			scale,
			images = [],
			timeoutId;

		function onScale(t, newScale) {
			scale = newScale;
			clearTimeout(timeoutId);

			hideCanvases();

			timeoutId = setTimeout(function() {
				$('.rich_pictures .preview canvas').each(function() {
					updateCanvas($(this));
				});

				showCanvases();
			}, 200);
		}

		function onImageLoad(el, index) {
			images[index].width < images[index].height && $(el).css('width', Math.round(images[index].width / images[index].height * 100) + '%');
			$c.support.canvas && createCanvas(el, index);
		}

		function showCanvases() {
			var els = $('.rich_pictures .preview');
			els.find('img.with_shape').addClass('hidden');
			els.find('canvas.shape').removeClass('hidden');
		}

		function hideCanvases() {
			var els = $('.rich_pictures .preview');
			els.find('img.with_shape').removeClass('hidden');
			els.find('canvas.shape').addClass('hidden');
		}

		function createCanvas(imgEl, index) {
			imgEl = $(imgEl).addClass('with_shape');
			var canvas = $('<canvas class="shape" />').insertBefore(imgEl).addClass(prefix + index);

			if (imgEl.hasClass('on_dark')) {
				canvas.addClass('on_dark');
			}
			if (imgEl.hasClass('on_light')) {
				canvas.addClass('on_light');
			}

			updateCanvas(canvas);
			imgEl.addClass('hidden');
		}

		function updateCanvas(el) {
			var
				index = $c.attrSuffix(el, prefix),
				k = 1 <= images[index].width / images[index].height ? 1 : Math.round(images[index].width / images[index].height * 100) / 100,
				width = Math.round((minWidth + (maxWidth - minWidth) * scale) * k),
				height = Math.round(images[index].height * width / images[index].width),
				ctx = el.get(0).getContext('2d');

			el.attr({
				height: height,
				width: width
			});
			ctx.drawImage(images[index], 0, 0, images[index].width, images[index].height, 0, 0, width, height);
		}

		function add(el) {
			if (!scale) {
				scale = photoSizer.getStep();
				$c.support.canvas && photoSizer.onScale(onScale);
			}

			var index = images.length;
			images[index] = new Image();
			$(images[index]).load(function() {
				onImageLoad(el, index);
			});
			images[index].src = el.src;
		}

		$('.rich_pictures .preview img').each(function() {
			add(this);
		});

		return { add: add };
	})();
});
