/**
 * @author Vlad Yakovlev (scorpix@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 * @version 0.1.2 (2009-09-17)
 * @requires jQuery
 * @requires jTweener 0.2.1
 */
var ie6FixPngImagePath = '/f/1/global/i/0.gif';

Common.Measurer = (function() {
	var funcs = {};

	var interval = 500;

	var genId =  1;

	var curHeight;

	var el;

	var isInit = false;

	var isDocReady = false;

	$(function() {
		isDocReady = true;
		isInit && initBlock();
	});

	function initBlock() {
		el = $('<div></div>').css({
			height: '1em',
			left: 0,
			lineHeight: '1em',
			position: 'absolute',
			top: '-1em',
			visibility: 'hidden',
			width: '100%'
		}).appendTo('body');
		curHeight = el.height();


		setInterval(function() {
			checkScale();
		}, interval);
		$(window).resize(callFuncs);
	}

	function checkScale() {
		var newHeight = el.height();

		if (newHeight != curHeight) {
			curHeight = newHeight;
			callFuncs();
		}
	}

	function callFuncs() {
		for (var func in funcs) {
			funcs[func]();
		}
	}

	return {
		setFunc: function(name, func) {
			if (!$.isFunction(name) && !$.isFunction(func)) {
				funcs[name] && (delete funcs[name]);

				return;
			}

			isInit = true;
			isDocReady && initBlock();

			if ($.isFunction(name)) {
				funcs[genId.toString()] = name;
				genId++;
			} else {
				funcs[name] = func;
			}
		}
	};
})();


Common.checkCanvas = function() {
	if (undefined !== window.HTMLCanvasElement)
		return true;

	// В IE для VML надо добавить схему и стили.
	if (!document.namespaces['v']) {
		document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');

		var ss = document.createStyleSheet();

		//ss.cssText = 'v\\:* {behavior:url(#default#VML);display:block;}';
		ss.cssText = '.vml {behavior:url(#default#VML);display:block;}';
	}

	return false;
}

Common.isCanvas = Common.checkCanvas();

if ($.browser.msie) {
	try {
		document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}

	function fixIePng(element) {
		if (!(/MSIE (5\.5|6).+Win/.test(navigator.userAgent))) {
			return;
		}

		var src;

		if ('IMG' == element.tagName || ('INPUT' == element.tagName && 'image' == element.type)) {
			if (/\.png$/.test(element.src)) {
				src = element.src;
				element.src = ie6FixPngImagePath;
			}
		} else {
			src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);

			if (src) {
				src = src[1];
				element.runtimeStyle.backgroundImage = 'none';
			}
		}

		var reScaleMode = /iesizing\-(\w+)/;
		var m = reScaleMode.exec(element.className);

		if (src) {
			var scaleMode = (m) ? m[1] : 'crop';
			element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='" + scaleMode + "')";
		}
	}
}



/**
 * Декоратор меню навигации.
 */
(function() {
	var className = 'shape';

	var blocks;

	var objects = [];

	var measurerHeight;

	var diff = 15;

	$(function() {
		blocks = {
			rootContainers: $('.main_navigation')
		};

		blocks.rootContainers.each(function() {
			var container = $(this).find('li.selected');

			if (!container.size()) {
				return;
			}

			objects.push({
				container: container,
				size: {
					height: Math.floor(container.outerHeight() / 2) * 2,
					width: container.outerWidth() + container.offset().left
				},
				color: $(this).css('color'),
				canvas: null,
				ctx: null
			});
		});

		blocks.measurer = $('<div class="measurer"></div>').appendTo(blocks.rootContainers.eq(0));

		measurerHeight = blocks.measurer.height();

		setInterval(checkMeasurer, 500);
	});

	$(window).load(function() {
		if (Common.isCanvas) {
			createCanvasShape();
			drawCanvasShape();
		} else {
			createVmlShape();
			drawVmlShape();
		}
	});

	function checkMeasurer() {
		var newHeight = blocks.measurer.height();

		if (newHeight != measurerHeight) {
			measurerHeight = newHeight;
			drawShape();
		}
	}

	function drawShape() {
		if (Common.isCanvas) {
			drawCanvasShape();
		} else {
			drawVmlShape();
		}
	}

	function createVmlShape() {
		for (var i = 0; i < objects.length; i++) {
			var canvas = document.createElement('v:shape');
			$(canvas).addClass('vml');

			canvas.style.width = objects[i].size.width + 'px';
			canvas.style.height = objects[i].size.height + 'px';
			canvas.filled = 'False';
			canvas.path = '';
			canvas.strokecolor = objects[i].color;
			$(canvas).addClass(className);
			$(canvas).prependTo(objects[i].container);
			objects[i].canvas = $(canvas);
		}
	}

	function drawVmlShape() {
		for (var i = 0; i < objects.length; i++) {
			objects[i].size = {
				height: Math.floor(objects[i].container.outerHeight() / 2) * 2,
				width: objects[i].container.outerWidth() + objects[i].container.offset().left
			};

			var width = objects[i].size.width;
			var height = objects[i].size.height;

			objects[i].canvas.css({
				height: height,
				width: width
			});
			objects[i].canvas.attr('coordsize', width + ',' + height);

			var radius = Math.floor(height / 2);

			objects[i].canvas.attr('path', 'm 0,' + diff + ' l ' + (width - radius) + ',0 qx ' + width + ',' + radius + ' ' + (width - radius) + ',' + height + ' l 0,' + (height - diff));
		}
	}

	function createCanvasShape() {
		for (var i = 0; i < objects.length; i++) {
			var canvas = $('<canvas class="' + className + '"></canvas>').prependTo(objects[i].container);

			canvas.attr({
				height: objects[i].size.height,
				width: objects[i].size.width
			});

			objects[i].canvas = canvas;
			objects[i].ctx = canvas.get(0).getContext('2d');
		}
	}

	function drawCanvasShape() {
		for (var i = 0; i < objects.length; i++) {
			objects[i].size = {
				height: Math.floor(objects[i].container.outerHeight() / 2) * 2,
				width: objects[i].container.outerWidth() + objects[i].container.offset().left
			};

			var width = objects[i].size.width;
			var height = objects[i].size.height;

			objects[i].canvas.attr({
				height: height,
				width: width
			});

			var ctx = objects[i].ctx;
			var radius = Math.floor(height / 2);

			ctx.strokeStyle = objects[i].color;
			ctx.beginPath();
			ctx.moveTo(0, diff);
			ctx.lineTo(width - radius, 0);
			ctx.arc(width - radius, radius, radius, -Math.PI / 2, Math.PI / 2, false);
			ctx.lineTo(0, height - diff);
			ctx.stroke();
			ctx.closePath();
		}
	}
})();



/**
 * Аниматор переключения изображений в "Подземном строительстве".
 */
(function() {
	var objects = [];

	$(function() {
		var blocks = $('#main_content .animate_pictures');

		blocks.each(function() {
			objects.push(new SectionAnimator($(this)));
		});
	});

	function SectionAnimator(rootBlock) {
		var blocks;

		var color;

		/**
		 * Ширина (<code>width</code>) и высота (<code>height</code>) блока-родителя.
		 */
		var rootSize;

		var radius;

		var className = 'shape';

		var current = 0;

		var selectedDescriptions = [];

		var animateDescriptions = [];

		var isAnimate = false;

		init();

		function init() {
			blocks = {
				root: rootBlock.find('.content'),
				container: rootBlock.find('.content .container'),
				images: rootBlock.find('.content .picture'),
				descriptions: rootBlock.find('.descriptions li')
			};
			color = $('body').css('background-color');
			rootSize = {
				height: blocks.root.height(),
				width: blocks.root.width()
			};
			radius = rootSize.height < rootSize.width ? Math.floor(rootSize.height / 2) : Math.floor(rootSize.width / 2);

			if (Common.isCanvas) {
				drawCanvasShape();
			} else {
				drawVmlShape();
			}

			blocks.descriptions.find('span').each(function(index) {
				$(this).click(function() {
					onChangeImage(index);
				});
			});

			initDescriptions();
		}

		function onChangeImage(index) {
			if (index == current || isAnimate) {
				return;
			}

			isAnimate = true;

			var curDescSize = {
				height: blocks.descriptions.eq(current).height(),
				width: blocks.descriptions.eq(current).width()
			};
			var newDescSize = {
				height: blocks.descriptions.eq(index).height(),
				width: blocks.descriptions.eq(index).width()
			};

			animateDescriptions[index].css({
				display: 'block',
				height: newDescSize.height,
				left: 0,
				opacity: 1,
				top: 0,
				width: newDescSize.width
			});
			selectedDescriptions[current].css({
				display: 'block',
				height: curDescSize.height,
				left: 0,
				opacity: 1,
				top: 0,
				width: curDescSize.width
			});

			var selectedDots = [0, current < index ? curDescSize.height : -curDescSize.height];
			var animateDots = [0, current < index ? newDescSize.height : -newDescSize.height];
			var curIndex = current;

			jTweener.removeTween(blocks.container);
			jTweener.addTween(blocks.container, {
				top: -index * rootSize.height,
				time: 1,
				moveX: function(value) {
					selectedDescriptions[curIndex].css({
						top: selectedDots[0] + Math.round((selectedDots[1] - selectedDots[0]) * value),
						opacity: 1 - value
					});
					animateDescriptions[index].css({
						top: animateDots[0] + Math.round((animateDots[1] - animateDots[0]) * value),
						opacity: 1 - value
					});
				},
				onComplete: function() {
					selectedDescriptions[curIndex].css('display', '');
					isAnimate = false;
				}
			});

			blocks.descriptions.eq(current).removeClass('selected');
			current = index;
			blocks.descriptions.eq(current).addClass('selected');
		}

		function initDescriptions() {
			blocks.descriptions.each(function() {
				var el = $(this);
				var html = el.html();

				var newDesc = $('<div class="animate_selected"></div>');

				newDesc.html(html).appendTo(el);
				selectedDescriptions.push(newDesc);
				newDesc = $('<div class="animate"></div>');
				newDesc.html(html).appendTo(el);
				animateDescriptions.push(newDesc);
			});
		}

		/**
		 * Отрисовывает форму с помощью VML.
		 */
		function drawVmlShape() {
			/**
			 * Элемент формы.
			 * @type {DomElement}
			 */
			var canvas = document.createElement('v:shape');
			var center = {
				x: Math.floor(rootSize.width / 2),
				y: Math.floor(rootSize.height / 2)
			};
			var width = rootSize.width;
			var height = rootSize.height;

			$(canvas).addClass(className);
			canvas.style.width = (rootSize.width + 1) + 'px';
			canvas.style.height = (rootSize.height + 1) + 'px';
			canvas.style.left = '-1px';
			canvas.style.top = '-1px';
			canvas.coordsize = rootSize.width + ' ' + rootSize.height;
			canvas.stroked = 'False';
			canvas.fillcolor = color;
			canvas.path = 'm 0,' + radius + ' qy ' + radius + ',0 l 0,0 0,' + radius + ' m ' + (width - radius) + ',0 qx ' + width + ',' + radius + ' l ' + width + ',0 ' + (width - radius) + ',0 m ' + width + ',' + (height - radius) + ' qy ' + (width - radius) + ',' + height + ' l ' + width + ',' + height + ' ' + width + ',' + (height - radius) + ' m ' + radius + ',' + height + ' qx 0,' + (height - radius) + ' l 0,' + height + ' ' + radius + ',' + height;
			$(canvas).appendTo(blocks.root);


		}

		/**
		 * Отрисовывает форму с помощью Canvas.
		 */
		function drawCanvasShape() {
			/**
			 * Элемент формы.
			 * @type {jQuery}
			 */
			var canvas = $('<canvas class="' + className + '"></canvas>').appendTo(blocks.root);

			canvas.attr('height', rootSize.height);
			canvas.attr('width', rootSize.width);

			/**
			 * Элемент контекста канваса.
			 */
			var ctx = canvas.get(0).getContext('2d');

			ctx.fillStyle = color;
			ctx.fillRect(0, 0, rootSize.width, rootSize.height);
			ctx.globalCompositeOperation = 'destination-out';
			ctx.beginPath();
			ctx.arc(Math.floor(rootSize.width / 2), Math.floor(rootSize.height / 2), radius, 0, 2 * Math.PI, true);
			ctx.fill();
			ctx.closePath();
		}
	}
})();



/**
 * Делает изображеня круглыми.
 * @param {jQuery} blocks Блоки, у которых, нужно сделать круглыми края.
 */
function RoundPicture(blocks) {
	var className = 'shape';

	blocks.each(function() {
		var el = $(this);
		var params = getElementParams(el);
		params.root = el;

		var image = new Image();
		params.image = image;
		image.onload = function() {
			var cssParams = {
				background: 'none',
				border: 0
			};

			if (params.borderWidth) {
				cssParams.width = params.width + params.borderWidth * 2;
				cssParams.height = params.height + params.borderWidth * 2;
			}

			el.css(cssParams);
			el.find('img').css('opacity', 0);

			if (Common.isCanvas) {
				createCanvas(params);
			} else {
				createVml(params);
			}
		};
		image.src = el.find('img').attr('src');
	});

	function createVml(params) {
		var radius = params.radius;
		var height = params.height;
		var width = params.width;
		var canvas = document.createElement('v:shape');

		$(canvas).addClass(className + ' vml');
		canvas.style.width = params.width + 'px';
		canvas.style.height = params.height + 'px';
		canvas.style.left = '0px';
		canvas.style.position = 'absolute';
		canvas.style.top = '0px';
		canvas.coordsize = params.width + ' ' + params.height;
		canvas.fillcolor = params.backColor;
		canvas.path = 'm ' + radius + ',0 l ' + (width - radius) + ',0 qx ' + width + ',' + radius + ' l ' + width + ',' + (height - radius) + ' qy ' + (width - radius) + ',' + height + ' l ' + radius + ',' + height + ' qx 0,' + (height - radius) + ' l 0,' + radius + ' qy ' + radius + ',0';

		var fillShape = document.createElement('v:fill');
		$(fillShape).addClass('vml');
		fillShape.color = params.backColor;
		fillShape.src = params.image.src;
		fillShape.type = 'frame';
		$(fillShape).appendTo(canvas);

		if (params.borderWidth) {
			var strokeShape = document.createElement('v:stroke');
			$(strokeShape).addClass('vml');
			strokeShape.color = params.borderColor;
			strokeShape.width = params.borderWidth + 'pt';
			$(strokeShape).appendTo(canvas);
		} else {
			canvas.stroked = 'False';
		}

		$(canvas).prependTo(params.root);
	}

	function createCanvas(params) {
		var canvas = $('<canvas class="' + className + '"></canvas>').prependTo(params.root).attr({
			height: params.height,
			width: params.width
		}).css({
			left: 0,
			position: 'absolute',
			top: 0
		});

		var ctx = canvas.get(0).getContext('2d');

		canvas.attr({
			height: params.height,
			width: params.width
		});
		ctx.fillStyle = params.backColor;
		drawShapeCanvas(params, ctx, params.borderWidth);

		if (params.image) {
			//ctx.globalCompositeOperation = 'source-in';
			ctx.globalCompositeOperation = 'source-atop';
			ctx.drawImage(params.image, 0, 0);
		}

		if (params.borderWidth) {
			ctx.globalCompositeOperation = 'destination-over';
			ctx.fillStyle = params.borderColor;
			drawShapeCanvas(params, ctx, 0);
		}
	}

	function drawShapeCanvas(params, ctx, border) {
		var radius = params.radius;
		var height = params.height;
		var width = params.width;

		ctx.beginPath();
		ctx.moveTo(radius + border, 0 + border);
		ctx.lineTo(width - radius - border, 0 + border);
		ctx.arc(width - radius, radius, radius - border, -Math.PI / 2, 0, false);
		ctx.lineTo(width - border, height - radius - border);
		ctx.arc(width - radius, height - radius, radius - border, 0, Math.PI / 2, false);
		ctx.lineTo(radius + border, height - border);
		ctx.arc(radius, height - radius, radius - border, Math.PI / 2, Math.PI, false);
		ctx.lineTo(0 + border ,radius + border);
		ctx.arc(radius, radius, radius - border, Math.PI, Math.PI * 3 / 2, false);
		ctx.fill();
		ctx.closePath();
	}

	function getElementParams(el) {
		var width = el.outerWidth();
		var height = el.outerHeight();

		var result = {
			backColor: el.css('background-color'),
			borderColor: el.css('border-top-color'),
			borderWidth: parseInt(el.css('border-top-width'))
		};

		if (!Common.isCanvas && result.borderWidth) {
			width -= result.borderWidth * 2;
			height -= result.borderWidth * 2;
		}

		result.radius = Math.round(width < height ? width / 2 : height / 2);
		result.height = result.radius * 2;
		result.width = result.radius * 2;

		return result;
	}
}

$(function() {
	RoundPicture($('.round_picture'));
});