/**
 * @author Vlad Yakovlev (scorpix@design.ru)
 * @copyright Art.Lebedev Studio (http://www.artlebedev.ru)
 */

function OpenWindow(sUri, iWidth, iHeight, connectionError)
{
	var errorCode = parseInt(connectionError);
	if (isNaN(errorCode)) {
		errorCode = 0
	}
	if (errorCode != 0 || isNaN(errorCode))
	{
		alert('ОШИБКА!\nВ настоящий момент нет связи с базой данных АНКОР.\nПопробуйте повторить попытку позже.')
		return null
	}
	else
	{
		var sWindowName = 'win' + Math.floor(Math.random() * 1000)
		var iRealWidth = iWidth ? iWidth : 600
		var iRealHeight = iHeight ? iHeight : screen.height - 300

		var iLeft = Math.round((screen.width - iRealWidth) / 2)
		var iTop = Math.round((screen.height - iRealHeight) / 2) - 35

		var sWindowOptions = 'status=yes,menubar=no,toolbar=no'
		sWindowOptions += ',resizable=no,scrollbars=yes,location=no'
		sWindowOptions += ',width=' + iRealWidth
		sWindowOptions += ',height=' + iRealHeight
		sWindowOptions += ',left=' + iLeft
		sWindowOptions += ',top=' + iTop

		var win = window.open(sUri, sWindowName, sWindowOptions)
		win.focus()

		return win
	}
}


var carcas = (function()
{
	/**
	 * Расстояние между блоками в em.
	 */
	var padding = 2;
	
	/**
	 * Смещение влево второго столбца в процентах.
	 */
	var column2Left = 25;
	
	/**
	 * Смещение влево третьего столбца в процентах.
	 */
	var column3Left = 80;

	/**
	 * Размер в пикселях одного em.
	 */
	var emK = 0;
	
	/**
	 * Текущий раскрытый блок.
	 */
	var currentId = '';
	
	/**
	 * Блок, ожидающий, когда его откроют.
	 */
	var queueId = '';
	
	/**
	 * Не дышать - идет процесс анимации блока.
	 */
	var busy = false;
	
	/**
	 * Надо бы закрыть текущий блок.
	 */
	var hide = false;
	
	var safariResize = false;
	
	var header2 = null;
	var header3 = null;
	var middle1 = null;
	var middle2 = null;
	var middle3 = null;
	var footer1 = null;
	var footer2 = null;
	var footer3 = null;
	var emLayout = null;
	var wrap = null;
	var layout = null;
	var header = null;
	var footer = null;
	
	$(window).load(function()
	{
		  if($.browser.mozilla && $.browser.version.substr(0,3)=="1.9"){
			     $('#header').css('width', '100%');
			$('#footer').css('width', '100%');
		}else{
			if($.browser.opera){
				$("#footer3").css("margin-right", "0px");
				$("#header3").css("margin-right", "0px");
			}
			  if($.browser.mozilla){
			$("#middle1").css("display", "table");}
			$('#footer2').css('width', '54%');
			$('#header2').css('width', '54%');
		}
		header2 = $('#header2');
		header3 = $('#header3');
		middle1 = $('#middle1');
		middle2 = $('#middle2');
		middle3 = $('#middle3');
		footer1 = $('#footer1');
		footer2 = $('#footer2');
		footer3 = $('#footer3');
		emLayout = $('#em-layout');
		wrap = $('#wrap');
		layout = $('#layout');
		header = $('#header');
		footer = $('#footer');
		
		if ($('#middle2>.round-corner').length)
			safariResize = true;
		
		$(window).resize(function()
		{
			emK = emLayout.height();

			if ($.browser.msie)
				ieResize();
			if ($.browser.safari || ($.browser.opera && 9.5 >= parseFloat($.browser.version)))
				advResize();
		}).resize();
		
		setInterval(function()
		{
			if (emK != emLayout.height())
				$(window).resize();
		}, 500);
		//$("body").css("padding-bottom", "1px");
		//$("body").css("padding-bottom", "0px");
	});
	
	/**
	 * Менеджер очереди.
	 */	
	function move(blockId)
	{
		
		if (blockId && blockId != currentId) 
		{	
			
			queueId = blockId;
			
			if (!busy)
				moveHide();
				
		}
		else 
		{
			queueId = '';
			
			if (busy)
				hide = true;
			else
				moveHide();
		}
		
		return false;
	}
	
	/**
	 * Вычисляет разницу в ширине/высоте между блоком и его потомком.
	 */
	function diffSize(id)
	{
		var parent = $('#' + id);
		var el = $('#' + id + ' .content');
		var elDiff = 0;
		var parentDiff = 0;
		

		switch (id)
		{
			case 'header3':
			case 'footer2':
			case 'footer3':
				elDiff = el.height();
				parentDiff = parent.height();
				break;
				
			case 'middle3':
			case 'footer1':
				elDiff = el.width();
				parentDiff = parent.width();
				
				break;
		}

		return elDiff > parentDiff ? elDiff - parentDiff : 0;
	}
	
	/**
	 * Возвращает размер в пикселях.
	 */
	function pixelSize(sizeString)
	{
		return -1 !== sizeString.toString().indexOf('em') ? parseInt(sizeString) * emK : parseInt(sizeString);
	}
	
	function endHide()
	{
		busy = false;
		
		if (queueId)
			moveShow();
	}
	
	function endShow()
	{
		busy = false;
		
		if (hide)
			moveHide();
	}

	function advResize()
	{
		if ($.browser.safari && !safariResize)
			return;

		var maxHeight = 0;
		
		$('.middle')
			.css('min-height', 0)
			.find('.content').each(function()
			{
				var height = $(this).height();
				
				if (maxHeight < height)
					maxHeight = height;
			}).end()
			.css('min-height', maxHeight).css('min-height', wrap.height());
	}

	function ieResize()
	{
		// {{{ Корректируем высоту
		var maxSectionHeight = 0;

		$('.middle .content').each(function()
		{
			var height = $(this).height();
			maxSectionHeight < height && (maxSectionHeight = height);
		});

		var contentHeight = $(window).height() - 20 * emK;

		if (contentHeight < maxSectionHeight)
			contentHeight = maxSectionHeight;

		layout.height(contentHeight);
		// }}} Корректируем высоту
		
		// Чтобы верхние блоки появились и принимали нужные размеры
		header.css('width', $('#wrap').width());
	}
	
	/**
	 * Анимация скрытия блока.
	 */
	function moveHide()
	{
		
		if (busy)
			return;
			
		hide = false;

		if (!currentId)
		{
			if (queueId)
				moveShow();
				
			return;
		}
		
		busy = true;
		operateId = currentId;
		currentId = '';
		

		switch (operateId)
		{
			case 'header3':
				
				// Переводим изменяемые размеры в пиксели
				header3.css('height', $('#header3').height());
				middle3.css('top', pixelSize($('#middle3').css('top')));
				
				var headerHeight = pixelSize(header.css('height'));
				var attrs = {};
				
				if ($.browser.msie) 
				{
					footer3.css('top', pixelSize(footer3.css('top')));
					attrs['top'] = 0;
				}
				else 
				{
					footer3.css('bottom', pixelSize(footer3.css('bottom')));
					attrs['bottom'] = 0;
				}
				
				header3.animate({ height: headerHeight }, 600, function()
				{
					header3.css('height', (header3.height() / emK) + 'em');
				});

				middle3.animate({ top: 0 }, 600);
				
				footer3.animate(attrs, 600, function()
				{
					// В Firefox появляется прокрутка при анимации :(
					if (!$.browser.msie)
						$('#footer-wrap').css('overflow', 'visible');

					endHide();
				});
				
				break;
				
			case 'middle3':
				var diff = diffSize('middle3');
				middle1.css('margin-left', -diff)
					.animate({ marginLeft: 0 }, 600, function()
					{
						endHide();
					});
				
				break;
				
			case 'footer1':
				var diff = diffSize('footer1');
				var footerWidth = footer.width();

				footer1
					.css('left', diff)
					.animate({ left: 0 }, 600);
				footer2
					//.css('left', footer.width() / 4 + diff)
					.animate({ left: 0}, 600);
				footer3
					//.css('left', footer.width() * 4 / 5 + diff)
					.animate({ left: 0 }, 600, function()
					{							
						$('#footer-wrap').css('overflow', 'visible');
						endHide();
					});
				
				break;
				
			case 'footer2':
				var footerHeight = $('#footer').height();
				
				header2.css('top', pixelSize(header2.css('top')));
				middle2.css('top', pixelSize(middle2.css('top')));
				
				footer2
					.css('height', footer2.height())
					.animate({ height: footerHeight, bottom: 0 }, 600, function()
					{
						footer2.css('height', (footerHeight / emK) + 'em');
					});
				
				$('#header2, #middle2').animate({ top: 0 }, 600, function()
				{
					endHide();
				});
				
				break;
				
			case 'footer3':
				var footerHeight = $('#footer').height();
				
				header3.css('top', pixelSize(header3.css('top')));
				middle3.css('top', pixelSize(header3.css('top')));
				
				$('#header3, #middle3').animate({ top: 0 }, 600);
				footer3
					.css('height', footer3.height())
					.animate({ bottom: '0px' }, 600, function()
					{
						footer3.css('height', (footerHeight / emK) + 'em');
						endHide();
					});
				
				break;
		}
	}
	
	/**
	 * Анимация показа блока.
	 */
	function moveShow()
	{
		if (busy)
			return;
			
		if (!queueId)
		{
			if (hide)
				moveHide();
				
			return;
		}
		
		var diff = diffSize(queueId);

		if (!diff) 
		{
			queueId = '';
			
			if (hide)
				moveHide();

			return;
		}

		busy = true;
		currentId = queueId;
		queueId = '';
		
		switch (currentId)
		{
			

			case 'header3':
				// В Firefox появляется прокрутка при анимации :(
				if (!$.browser.msie)
					$('#footer-wrap').css('overflow', 'hidden');

				header3.css('height', header3.height());
				
				var headerHeight = pixelSize(header.css('height'));
				var attrs = {};
				
				if ($.browser.msie)
				// В IE косячит смещение по нижней границе.
					attrs['top'] = diff;
				else 
					attrs['bottom'] = -diff;
				
				header3.animate({ height: headerHeight + diff }, 600, function()
				{
					header3.css('height', (header3.height() / emK) + 'em');
				});
				
				middle3.animate({ top: diff }, 600, function()
				{
					middle3.css('top', (pixelSize(middle3.css('top')) / emK) + 'em');
				});

				footer3.animate(attrs, 600, function()
				{
					if ($.browser.msie)
						footer3.css('top', (pixelSize(footer3.css('top')) / emK) + 'em')
					else
						footer3.css('bottom', (pixelSize(footer3.css('bottom')) / emK) + 'em')
						
					endShow();
				});
				
				break;
				
			case 'middle3':
				var perCent = diff / footer.width() * 100;
				middle1.animate({ marginLeft: -diff }, 600, function()
				{
					middle1.css('margin-left', -perCent + '%');
					endShow();
				});
				
				break;
				
			case 'footer1':
				if (!$.browser.msie) 
				{
					$('#footer-wrap').css('overflow', 'hidden');
					footer1.css('overflow', 'visible');
				}
				
				var footerWidth = footer.width();
				var perCent = diff / footerWidth * 100;
				
				footer1
					.css('left', 0)
					.animate({ left: diff }, 600, function()
					{
						footer1.css('left', perCent + '%');
					});
				footer2
					//.css('left', footerWidth / 4)
					.animate({ left: diff }, 600);
				footer3
					//.css('left', footerWidth * 4 / 5)
					.animate({ left: diff }, 600, function()
					{
						
						endShow();
					});
				
				break;
				
			case 'footer2':
				footer2
					.css('height', footer2.height())
					.animate({ bottom:diff, height:footer.height() + diff }, 600, function()
					{
						footer2.css('height', (footer2.height() / emK) + 'em');
					});
				
				$('#header2, #middle2').animate({ top: -diff }, 600, function()
				{
					$('#header2, #middle2').css('top', (-diff / emK) + 'em');
					endShow();
				});
				
				break;
				
			case 'footer3':
				

				var footerHeight = footer.height();

				if ($.browser.msie)
					footer3.css('top', 'auto');
					
				footer3
					.css('height', pixelSize(footer3.height())).animate({ bottom: diff }, 600);
					footer3.css('height', ((footerHeight + diff) / emK) + 'em');
					
					
				
				$('#header3, #middle3').animate({ top: -diff }, 600, function()
				{
					$('#header3, #middle3').css('top', (-diff / emK) + 'em');
					endShow();
				});
				
				break;
		}
	}
	
	function getEmK()
	{
		return emK;
	}
	
	return {
		getEmK:   getEmK,
		ieResize: ieResize,
		move:     move
	};
})();

$(function()
{
	$('#header3 .action span').click(function() { carcas.move('header3'); });
	$('#middle3 .action span').click(function() { carcas.move('middle3'); });
	$('#footer1 .action span').click(function() { carcas.move('footer1'); });
	$('#footer2 .action span').click(function() { carcas.move('footer2'); });
	$('#footer3 .action span').click(function() { carcas.move('footer3'); });
});

$(window).load(
	function(){
		if($.browser.msie){
			setTimeout(function(){$("#layout").css('position', 'static');}, 100);
			setTimeout(function(){$("#layout").css('position', 'relative');}, 200);
		}else{
			$("#layout").css('position', 'static');
			setTimeout(function(){$("#layout").css('position', 'relative');},1);

		}
		}
);