/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 */
$(function() {
	function mapLight(imgEl, hoverOptions, selectedOptions, options) {
		var defOptions = {
			fill: true,
			fillColor: '000000',
			fillOpacity: 0,
			stroke: true,
			strokeColor: 'ff0000',
			strokeOpacity: 0,
			strokeWidth: 0,
			pattern: './pages/space/fader.png'
		};

		var
			canvasStyle = {
				position: 'absolute',
				left: 0,
				top: 0,
				padding: 0,
				border: 0
			};

		var
			wrap,
			map,
			canvas,
			current = -1,
			areaEls = [],
			hoverPatternId = 'p' + Math.round(10000 * Math.random()),
			selectedPatternId = 'p' + Math.round(10000 * Math.random());

		init();

		function init() {
			imgEl = $(imgEl)
			hoverOptions = $.extend({}, defOptions, hoverOptions);
			selectedOptions = $.extend({}, defOptions, selectedOptions);
			options = $.extend({}, {
				onSelect: null,
				first: -1
			}, options);
			map = $('map[name="' + imgEl.attr('usemap').substr(1) + '"]');

			if (!(imgEl.is('img') && imgEl.attr('usemap') && map.size() > 0)) return;

			wrap = $('<div>').css({
				display: 'block',
				background: 'url(' + imgEl[0].src + ')',
				position: 'relative',
				padding: 0,
				width: imgEl[0].width,
				height: imgEl[0].height
			});
			imgEl.before(wrap).css('opacity', 0).css(canvasStyle);

			if ($.browser.msie) {
				imgEl.css('filter', 'Alpha(opacity=0)');
			}

			wrap.append(imgEl);

			canvas = $c.support.svg ? createCanvasForSvg(imgEl[0], hoverOptions, selectedOptions) : createCanvasForVml(imgEl[0]);

			$(map).find('area[coords]').each(function(index) {
				var shape = shapeFromArea(this);
				var el = $c.support.svg
					? addShapeToSvg(canvas, shape[0], shape[1], defOptions)
					: addShapeToVml(canvas, shape[0], shape[1], defOptions);

				areaEls.push(el);

				$(this).mouseover(function() {
					if (index == current) return;
					$c.support.svg ? updateStateSvg(el, hoverOptions) : updateStateVml(el, hoverOptions);
				}).mouseout(function() {
					if (index == current) return;
					$c.support.svg ? updateStateSvg(el, defOptions) : updateStateVml(el, defOptions);
				}).click(function() {

					if (options.onSelect && !options.onSelect(index)) return false;

					if (-1 < current) {
						$c.support.svg ? updateStateSvg(areaEls[current], defOptions) : updateStateVml(el, defOptions);
					}

					$c.support.svg ? updateStateSvg(el, selectedOptions) : updateStateVml(el, selectedOptions);
					current = index;

					return false;
				});
			});

			imgEl.before(canvas); // if we put this after, the mouseover events wouldn't fire.

			if (-1 < options.first) {
				$c.support.svg ? updateStateSvg(areaEls[options.first], selectedOptions) : updateStateVml(areaEls[options.first], selectedOptions);
				current = options.first;
			}
		}

		function createCanvasForSvg(img, hoverOptions, selectedOptions) {
			var c = document.createElementNS($c.ns.svg, 'svg');
			c.setAttribute('version', '1.1');
			c.setAttribute('viewBox', [0, 0, img.width, img.height].join(' '));
			c.style.width = img.width + 'px';
			c.style.height = img.height + 'px';

			for (var cssName in canvasStyle) {
				c.style[cssName] = canvasStyle[cssName];
			}

			return c;
		}

		function addShapeToSvg(canvas, shape, coords, options) {

			var shapeEl;

			switch (shape) {
				case 'rect':
					shapeEl = document.createElementNS($c.ns.svg, 'rect');
					shapeEl.setAttribute('x', coords[0]);
					shapeEl.setAttribute('y', coords[1]);
					shapeEl.setAttribute('width', coords[2] - coords[0]);
					shapeEl.setAttribute('height', coords[3] - coords[1]);

					break;

				case 'poly':
					shapeEl = document.createElementNS($c.ns.svg, 'polygon');
					shapeEl.setAttribute('points', coords.join(','));

					break;

				case 'circ':
					shapeEl = document.createElementNS($c.ns.svg, 'circle');
					shapeEl.setAttribute('cx', coords[0]);
					shapeEl.setAttribute('cy', coords[1]);
					shapeEl.setAttribute('r', coords[2]);

					break;
			}

			if (!shapeEl) return;

			shapeEl.setAttribute('fill', options.fillColor);
			shapeEl.setAttribute('stroke', '#' + options.strokeColor);
			shapeEl.setAttribute('stroke-width', '#' + options.strokeWidth);
			shapeEl.setAttribute('opacity', options.fill ? options.fillOpacity : 0);
			$(canvas).append(shapeEl);

			return shapeEl;
		}

		function updateStateSvg(el, options) {
			el.setAttribute('fill', '#' + options.fillColor);
			el.setAttribute('stroke', '#' + options.strokeColor);
			el.setAttribute('stroke-width', options.strokeWidth);
			el.setAttribute('opacity', options.fillOpacity);
		}

		function createCanvasForVml(img) {
			var c = $('<var style="zoom:1;overflow:hidden;display:block;width:' + img.width + 'px;height:' + img.height + 'px;"></var>');
			c.css(canvasStyle);

			return c[0];
		}

		function addShapeToVml(canvas, shape, coords, options) {
			var
				fill = '<v:fill color="#' + options.fillColor + '" opacity="' + (options.fill ? options.fillOpacity : 0) + '" />',
				stroke = 'strokeweight="' + options.strokeWidth + '" stroked="t" strokecolor="#' + options.strokeColor + '"',
				opacity = '<v:stroke opacity="' + options.strokeOpacity + '"/>',
				e;

			if (shape == 'rect') {
				e = $('<v:rect filled="t" ' + stroke + ' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:' + coords[0]+'px;top:'+coords[1]+'px;width:'+(coords[2] - coords[0])+'px;height:'+(coords[3] - coords[1])+'px;"></v:rect>');
			} else if(shape == 'poly') {
				e = $('<v:shape filled="t" ' + stroke + ' coordorigin="0,0" coordsize="' + canvas.width + ',' + canvas.height + '" path="m '+coords[0]+','+coords[1]+' l '+coords.join(',')+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+canvas.width+'px;height:'+canvas.height+'px;"></v:shape>');
			} else if(shape == 'circ') {
				e = $('<v:oval filled="t" ' + stroke + ' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:' + (coords[0] - coords[2])+'px;top:'+(coords[1] - coords[2])+'px;width:'+(coords[2]*2)+'px;height:'+(coords[2]*2)+'px;"></v:oval>');
			}

			e.get(0).innerHTML = fill + opacity;
			$(canvas).append(e);

			return e[0];
		}

		function updateStateVml(el, options) {
			$(el).find('fill').attr('color', '#' + options.fillColor);
			$(el).attr('strokecolor', '#' + options.strokeColor);
			$(el).attr('strokewidth', options.strokeWidth);
			$(el).find('fill').attr('opacity', options.fillOpacity);
		}

		function shapeFromArea(area) {
			var coords = area.getAttribute('coords').split(',');

			for (var i = 0; i < coords.length; i++) {
				coords[i] = parseFloat(coords[i]);
			}

			return [area.getAttribute('shape').toLowerCase().substr(0,4), coords];
		}
	}

	var
		rootEl = $('#content .main_picture'),
		roomsEl = $('#content .rooms'),
		selectedIndex = 0,
		isAnimate = false,
		nextIndex = -1;

	roomsEl.find('.room').eq(selectedIndex).addClass('room_selected');

	mapLight($('#content .main_picture img'), {
		fillColor: 'ec008c',
		fillOpacity: 0.2,
		stroke: false,
		fill: false
	}, {
		fillColor: 'ec008c',
		fillOpacity: .4,
		stroke: false,
		fill: false
	}, {
		onSelect: select,
		first: selectedIndex
	});

	function select(index) {
		if (index == selectedIndex) return false;

		if (isAnimate) {
			nextIndex = index;

			return true;
		}

		isAnimate = true;

		var
			curEl = false,
			curHeight = 0,
			newEl = roomsEl.find('.room').eq(index),
			newHeight;

		roomsEl.height(roomsEl.height());

		if (-1 < selectedIndex) {
			curEl = roomsEl.find('.room').eq(selectedIndex);
			curEl.css('position', 'absolute');
			curHeight = curEl.height();
		}

		newEl.css({
			display: 'block',
			position: 'absolute'
		});
		newHeight = newEl.height();
		newEl.css('top', newHeight > curHeight ? -newHeight : curHeight);

		false === curEl || jTweener.addTween(curEl, {
			time: 1,
			top: newHeight > curHeight ? newHeight : -curHeight
		});
		jTweener.addTween(newEl, {
			time: 1,
			top: 0
		});
		jTweener.addTween(roomsEl, {
			time: 1,
			height: newHeight,
			onComplete: function() {
				if (false !== curEl) {
					curEl.css({
						position: '',
						top: ''
					}).removeClass('room_selected');
				}

				newEl.css({
					display: '',
					position: '',
					top: ''
				}).addClass('room_selected');
				roomsEl.css('height', '');

				selectedIndex = index;
				isAnimate = false;

				if (-1 < nextIndex) {
					select(nextIndex);
					nextIndex = -1;
				}
			}
		});

		return true;
	}
});


$(function() {
	var linkEls = $('#content .reservation .variants .pseudo');
	var sectionEls = $('#content .reservation .container');

	linkEls.each(function(index) {
		$(this).click(function() {
			if ($(this).hasClass('selected')) {
				sectionEls.eq(index).removeClass('container_selected');
				linkEls.eq(index).removeClass('selected');
			} else {
				sectionEls.removeClass('container_selected');
				linkEls.removeClass('selected');

				sectionEls.eq(index).addClass('container_selected');
				linkEls.eq(index).addClass('selected');
			}
		});
	});
});