/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 * @requires jQuery
 * @requires jCommon
 * @version 0.1
 * @date 2010-03-18
 */

$(function() {

	function circleImages(rootEl) {
		rootEl = $(rootEl);

		if (!rootEl.length) return;

		var
			/**
			 * Часть окружности, которую заполняют слова.
			 */
			sector = .85,//0.75,
			/**
			 * Радиус окружности.
			 */
			radius = 200,

			innerRadius = radius - 3,

			outerRadius = radius + 3,
			/**
			 * Масштаб окружности.
			 */
			scale = 2,

			svgWidth = 430,

			svgHeight = 430,

			textSize = 15,

			curTextSize = 23,

			duration = 300;

		var

			circleEl = rootEl.find('.circle'),

			eventEls = rootEl.find('.event'),

			transformEl,

			blocks = [],

			/**
			 * Ширина все текстовых блоков.
			 */
			fullWidth = 0,
			/**
			 * Длина окружности.
			 */
			circleWidth = 2 * Math.PI * radius * sector,

			curIndex = -1,

			curRotate = 0;

		init();
		animate(0);

		rootEl.click(function(evt) {
			var index = $(evt.target).data('textIndex');

			if (null === index || undefined === index) {
				return;
			}

			index = parseInt(index);

			if (index != curIndex) {
				animate(index);
			}

			return false;
		});

		function init() {

			if (!$c.browser.msie) {
				eventEls.css('opacity', 0);
			}

			eventEls
				.css({
					display: 'block',
					visibility: 'hidden'
				})
				.each(function() {
					var el = $(this).find('dt');

					el.css('font-size', textSize);
					var width = el.width();
					el.css('font-size', curTextSize);
					var bigWidth = el.width();

					blocks.push({
						text: el.text(),
						width: width,
						bigWidth: bigWidth
					});
					fullWidth += width;
					el.addClass('hidden');
				})
				.css({
					display: '',
					visibility: ''
				});

			var halfWidth = 0;

			if ($c.support.svg) {

				var svgEl = $c.svg('svg')
					.svgAttr('viewBox', [0, 0, svgWidth * scale, svgHeight * scale].join(' '))
					.svgCss({
						height: svgHeight,
						width: svgWidth
					})
					.appendTo(circleEl);

				transformEl = $c.svg('g').appendTo(svgEl);
				transformEl.svgAttr('transform', 'translate(' + svgWidth + ',' + svgHeight + ')');

				var gEl = $c.svg('g').appendTo(transformEl);
				gEl.svgAttr('transform', 'translate(-' + svgWidth + ',-' + svgHeight + ')');

				var defsEl = $c.svg('defs').appendTo(svgEl);

				/**
				 * Создаем элемент пути для текстовых элементов.
				 */

				var pathTextId = getId();
				var pathTextEl = $c.svg('path')
					.svgAttr({
						transform: 'translate(24,24)',
						id: pathTextId,
						d: 'M 400,0 a 400,400 0 0,1 0,800 a 400,400 0 0,1 0,-800'
					})
					.appendTo(defsEl);

				/**
				 * Создаем текстовые блоки.
				 */

				var textEl = $c.svg('text')
					.svgAttr({
						fill: '#000'
					})
					.svgCss({
						fontSize: textSize * scale
					})
					.appendTo(gEl);

				$.each(blocks, function(index) {
					var
						id = getId(),
						innerId = getId(),
						part1 = halfWidth / fullWidth * sector + (this.width / fullWidth - this.width / circleWidth) / 2,
						part2 = part1 + this.width / circleWidth * sector;

					blocks[index].id = id;
					blocks[index].innerId = innerId;
					blocks[index].halfWidth = halfWidth;
					blocks[index].part1 = part1;
					blocks[index].part2 = part2;

					$c.svg('textPath')
						.svgAttr({
							id: id,
							startOffset: (Math.round(part1 * 10000) / 100) + '%',
							href: '#' + pathTextId
						})
						.svgCss('cursor', 'pointer')
						.text(this.text)
						.appendTo(textEl)
						.data('textIndex', index);

					/**
					 * Подчеркивание текста.
					 */

					$c.svg('path')
						.svgAttr({
							transform: 'translate(24,24)',
							d: linePath(innerRadius, getAngle(part1), getAngle(part2)),
							id: innerId,
							fill: 'none',
							stroke: '#000',
							strokeWidth: 1
						})
						.appendTo(gEl);

					if (index) {
						/**
						 * Линия между двумя блоками текста.
						 */

						var
							outerId = getId(),
							outerPart1 = blocks[index - 1].part2 + 1 / 180,
							outerPart2 = part1 - 1 / 180,
							outerAngle1 = getAngle(outerPart1),
							outerAngle2 = getAngle(outerPart2);

						$c.svg('path')
							.svgAttr({
								transform: 'translate(24,24)',
								d: linePath(outerRadius, outerAngle1, outerAngle2),
								id: outerId,
								fill: 'none',
								stroke: '#000',
								strokeWidth: 1
							})
							.appendTo(gEl);

						blocks[index].outerId = outerId;
						blocks[index].outerPart1 = outerPart1;
						blocks[index].outerPart2 = outerPart2;
					}

					halfWidth += this.width;
				});

			} else if ($c.support.vml) {
				var gEl = $(document.createElement('v:group'));
				gEl
					.attr({
						coordorigin: '0,0',
						coordsize: svgWidth + ',' + svgHeight
					})
					.css({
						height: svgHeight,
						left: 0,
						position: 'absolute',
						top: 0,
						width: svgWidth
					})
					.appendTo(circleEl);

				transformEl = gEl;

				$.each(blocks, function(index) {
					var
						id = getId(),
						innerId = getId(),
						part1 = halfWidth / fullWidth * sector + (this.width / fullWidth - this.width / circleWidth) / 2,
						part2 = part1 + this.width / circleWidth * sector;

					blocks[index].id = id;
					blocks[index].innerId = innerId;
					blocks[index].halfWidth = halfWidth;
					blocks[index].part1 = part1;
					blocks[index].part2 = part2;

					var arcEl = $(document.createElement('v:arc'))
						.attr({
							startangle: getAngle(part1),
							endangle: getAngle(part2),
							filled: 'True',
							stroked: 'False',
							fillcolor: '#000'
						})
						.css({
							cursor: 'pointer',
							height: svgHeight,
							left: 0,
							position: 'absolute',
							top: 0,
							width: svgWidth
						})
						.appendTo(gEl)
						.data('textIndex', index);

					$(document.createElement('v:path'))
						.attr({
							textpathok: 'True'
						})
						.css({
							cursor: 'pointer'
						})
						.appendTo(arcEl);

					$(document.createElement('v:textpath'))
						.attr({
							on: 'True',
							string: this.text
						})
						.css({
							fontSize: textSize,
							textDecoration: 'underline'
						})
						.appendTo(arcEl);

					/**
					 * Подчеркивание текста.
					 */

					$(document.createElement('v:arc'))
						.attr({
							startangle: getAngle(part1),
							endangle: getAngle(part2),
							filled: 'False'
						})
						.css({
							height: svgHeight - textSize,
							left: textSize / 2,
							position: 'absolute',
							top: textSize / 2,
							width: svgWidth - textSize
						})
						.appendTo(gEl);

					if (index) {
						/**
						 * Линия между двумя блоками текста.
						 */

						var
							outerId = getId(),
							outerPart1 = blocks[index - 1].part2 + 1 / 180,
							outerPart2 = part1 - 1 / 180,
							outerAngle1 = getAngle(outerPart1),
							outerAngle2 = getAngle(outerPart2);

						$(document.createElement('v:arc'))
							.attr({
								startangle: outerAngle1,
								endangle: outerAngle2,
								filled: 'False'
							})
							.css({
								height: svgHeight,
								left: 0,
								position: 'absolute',
								top: 0,
								width: svgWidth
							})
							.appendTo(gEl);

						blocks[index].outerId = outerId;
						blocks[index].outerPart1 = outerPart1;
						blocks[index].outerPart2 = outerPart2;
					}

					halfWidth += this.width;
				});
			}
		}

		function animate(index) {

			if (-1 == curIndex) {
				if (!$c.browser.msie) {
					eventEls.eq(index)
						.css('display', 'block')
						.animate({
							opacity: 1
						}, {
							duration: 2 * duration
						})
				}

				animateText(index, 2 * duration);
			} else {

				var tEl = eventEls.eq(curIndex);

				if (!$c.browser.msie) {
					tEl.animate({
						opacity: 0
					}, {
						duration: duration,
						complete: function() {
							tEl.css('display', '');
						}
					});
				}

				animateText(curIndex, duration, true, function() {
					if (!$c.browser.msie) {
						eventEls.eq(index)
							.css('display', 'block')
							.animate({
								opacity: 1
							}, {
								duration: duration
							})
					}

					animateText(index, duration);
				});
			}

			var
				startRotate = curRotate,
				endRotate = getRotate(index);

			if ($c.support.svg) {
				transformEl.animate({ moveX: 1 }, {
					duration: 2 * duration,
					step: function(t, o) {
						var rotate = startRotate + (endRotate - startRotate) * o.pos;

						transformEl.svgAttr('transform', 'translate(' + svgWidth + ',' + svgHeight + ') rotate(' + rotate + ')');
					},
					complete: function() {
						curRotate = endRotate;
					}
				});
			} else if ($c.support.vml) {
				transformEl.animate({ moveX: 1 }, {
					duration: 2 * duration,
					step: function(t, o) {
						var rotate = startRotate + (endRotate - startRotate) * o.pos;

						transformEl.css('rotation', rotate);
					},
					complete: function() {
						curRotate = endRotate;
					}
				});
			}

			eventEls.eq(curIndex).removeClass('selected');
			eventEls.eq(index).addClass('selected');
			curIndex = index;
		}

		function animateText(index, duration, isCurrent, callback) {
			if (!$c.support.svg) return;

			var
				block = blocks[index],
				nextBlock = blocks.length - 1 > index ? blocks[index + 1] : null,
				textPathEl = circleEl.find('#' + block.id),
				innerEl = circleEl.find('#' + block.innerId),
				outerEl1 = index ? circleEl.find('#' + block.outerId) : null,
				outerEl2 = blocks.length - 1 > index ? circleEl.find('#' + nextBlock.outerId) : null;

			if (isCurrent) {
				var
					startTextSize = curTextSize * scale,
					endTextSize = textSize * scale,

					startTextOffset = block.part1 + (block.width - block.bigWidth) / 2 / circleWidth * sector,
					endTextOffset = block.part1,

					offset = startTextOffset + block.bigWidth / circleWidth * sector,

					startAngle1 = getAngle(startTextOffset),
					startAngle2 = getAngle(offset),
					endAngle1 = getAngle(block.part1),
					endAngle2 = getAngle(block.part2);

				if (outerEl1) {
					var
						startOuter1Angle1 = getAngle(block.outerPart1),
						startOuter1Angle2 = getAngle(startTextOffset - 1 / 180),
						endOuter1Angle1 = getAngle(block.outerPart1),
						endOuter1Angle2 = getAngle(block.outerPart2);
				}
				if (outerEl2) {
					var
						startOuter2Angle1 = getAngle(offset + 1 / 180),
						startOuter2Angle2 = getAngle(nextBlock.outerPart2),
						endOuter2Angle1 = getAngle(nextBlock.outerPart1),
						endOuter2Angle2 = getAngle(nextBlock.outerPart2);
				}
			} else {

				var
					startTextSize = textSize * scale,
					endTextSize = curTextSize * scale,

					startTextOffset = block.part1,
					endTextOffset = block.part1 + (block.width - block.bigWidth) / 2 / circleWidth * sector,

					offset = endTextOffset + block.bigWidth / circleWidth * sector,

					startAngle1 = getAngle(block.part1),
					startAngle2 = getAngle(block.part2),
					endAngle1 = getAngle(endTextOffset),
					endAngle2 = getAngle(offset);

				if (outerEl1) {
					var
						startOuter1Angle1 = getAngle(block.outerPart1),
						startOuter1Angle2 = getAngle(block.outerPart2),
						endOuter1Angle1 = getAngle(block.outerPart1),
						endOuter1Angle2 = getAngle(endTextOffset - 1 / 180);
				}
				if (outerEl2) {
					var
						startOuter2Angle1 = getAngle(nextBlock.outerPart1),
						startOuter2Angle2 = getAngle(nextBlock.outerPart2),
						endOuter2Angle1 = getAngle(offset + 1 / 180),
						endOuter2Angle2 = getAngle(nextBlock.outerPart2);
				}
			}

			circleEl.animate({ moveX: 1 }, {
				duration: duration,
				step: function(t, o) {
					var value = o.pos;

					textPathEl
						.svgCss('font-size', startTextSize + (endTextSize - startTextSize) * value)
						.svgAttr('startOffset', ((startTextOffset + (endTextOffset - startTextOffset) * value) * 100) + '%');

					var
						angle1 = startAngle1 + (endAngle1 - startAngle1) * value,
						angle2 = startAngle2 + (endAngle2 - startAngle2) * value;

					innerEl.svgAttr('d', linePath(innerRadius, angle1, angle2));

					if (outerEl1) {
						angle1 = startOuter1Angle1 + (endOuter1Angle1 - startOuter1Angle1) * value;
						angle2 = startOuter1Angle2 + (endOuter1Angle2 - startOuter1Angle2) * value;

						outerEl1.svgAttr('d', linePath(outerRadius, angle1, angle2));
					}

					if (outerEl2) {
						angle1 = startOuter2Angle1 + (endOuter2Angle1 - startOuter2Angle1) * value;
						angle2 = startOuter2Angle2 + (endOuter2Angle2 - startOuter2Angle2) * value;

						outerEl2.svgAttr('d', linePath(outerRadius, angle1, angle2));
					}
				},
				complete: function() {
					callback && callback();
				}
			});
		}

		function linePath(curRadius, startAngle, endAngle) {
			var
				startX = Math.round(scale * (radius + Math.cos(getRad(startAngle)) * curRadius)),
				startY = Math.round(scale * (radius + Math.sin(getRad(startAngle)) * curRadius)),
				endX = Math.round(scale * (radius + Math.cos(getRad(endAngle)) * curRadius)),
				endY = Math.round(scale * (radius + Math.sin(getRad(endAngle)) * curRadius));

			return 'M ' + startX + ',' + startY + ' A ' + (scale * radius) + ',' + (scale * radius) + ' 0 0,1 ' + endX + ',' + endY;
		}

		function getAngle(value) {
			if ($c.support.svg) {
				return value * 360 - 90;
			}

			return value * 360;
		}

		function getRotate(index) {
			return -360 * (blocks[index].part1 + (blocks[index].part2 - blocks[index].part1) / 2);
		}

		function getId() {
			return 'id' + Math.round(Math.random() * 1000000);
		}

		function getRad(deg) {
			return deg * Math.PI / 180;
		}
	}

	circleImages('#content .events');

	(function() {
		var duration = 300;

		$('.back_pictures .back_main').insertBefore($('#footer'));

		var
			layoutEl = $('#layout'),
			imgEls = $('.back_pictures img'),
			contentEl = $('#content, #navigation, #header .from_blogs'),
			pictureEls = $('.back_main .pictures .picture'),
			fadeEl = $('.back_pictures .fade'),

			fadeOpacity = fadeEl.css('opacity'),
			curIndex = 0;

		imgEls.not('.selected').css('opacity', 0);
		showEl(contentEl, { notIe: true });

		pictureEls.each(function(index) {
			var el = $(this);

			if (!$c.browser.msie) {
				el.find('.description').css('opacity', 0);
			}

			el.find('.pseudo').click(function() {

				if (curIndex == index) {
					if (layoutEl.hasClass('light')) {
						hideEl(el.find('.description'), { notIe: true });
						showEl(fadeEl, { opacity: fadeOpacity });
						setLight(false);
					} else {
						showEl(el.find('.description'), { notIe: true });
						hideEl(fadeEl);
						setLight(true);
					}
				} else {
					if (layoutEl.hasClass('light')) {
						hideEl(pictureEls.eq(curIndex).find('.description'), { notIe: true });
						showEl(pictureEls.eq(index).find('.description'), { notIe: true });
						hideEl(imgEls.eq(curIndex));
						showEl(imgEls.eq(index));
						setCurrent(index);
					} else {
						hideEl(imgEls.eq(curIndex));
						showEl(imgEls.eq(index));
						setCurrent(index);
					}
				}
			});
		});

		function setLight(light) {
			if (light) {
				layoutEl.addClass('light');
				hideEl(contentEl, { notIe: true });
			} else {
				layoutEl.removeClass('light');
				showEl(contentEl, { notIe: true });
			}
		}

		function setCurrent(index) {
			imgEls.eq(curIndex).removeClass('selected');
			pictureEls.eq(curIndex).removeClass('selected');
			imgEls.eq(index).addClass('selected');
			pictureEls.eq(index).addClass('selected');

			curIndex = index;
		}

		function showEl(el, options) {

			options = $c.extend(options, {
				notIe: false,
				opacity: 1
			});

			el.css('visibility', 'visible');

			if (!(options.notIe && $c.browser.msie)) {
				el
					.stop()
					.animate({
						opacity: options.opacity
					}, {
						duration: duration
					});
			}
		}

		function hideEl(el, options) {
			options = $c.extend(options, {
				notIe: false
			});

			if (options.notIe && $c.browser.msie) {
				el.css('visibility', 'hidden');
			} else {
				el
					.css('visibility', 'visible')
					.stop()
					.animate({
						opacity: 0
					}, {
						duration: duration,
						complete: function() {
							el.css('visibility', 'hidden');
						}
					});
			}
		}
	})();

	(function() {

		var
			rootEl = $('#content .events'),
			faderEl = $('.fader');

		rootEl.find('.item').each(function() {
			var
				itemEl = $(this),
				linkEl = itemEl.find('>img, .name .pseudo'),
				popupEl = itemEl.find('.popup'),
				closeEl = popupEl.find('.icon_close');

			if (linkEl) {
				popupEl.appendTo('body');
				$c.popupBlock(popupEl, {
					link: linkEl,
					close: closeEl,
					fader: faderEl
				});
			}
		});
	})();

});
