jQuery(function($) {
	var $body = $('body');

	var structureModal = {};
	
	var modal = {};
	
	var images;
	
	var ajaxLink;
	
	var activeImage;
	
	var animateSpeed = 200;
	
	/*var userAgent = navigator.userAgent.toLowerCase();
	var browserVersion = (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1];
	var isIE6 = (/msie|MSIE 6/.test(userAgent) && !/opera/.test(userAgent) && parseInt(browserVersion) < 7);*/

	var isIE6 = false;

	if (window.external && (typeof window.XMLHttpRequest == "undefined")) {
		isIE6 = true;
	}

	var element;
	
	$.fn.PwModal = function(settings) {
		if (!this)
			return false;
		
		element = this;
		
		init();
		
		if ($(this).attr('rel')) {
			var list = $('[rel=' + $(this).attr('rel') + ']');
			
			if (list.size() > 1) {
				modal.isGallery = true;
			}
			
			activeImage = list.index(this);
			var img = new Array();
			$(list).each(function(){
				var image = {};
				image.preview = $(this).children('img').attr('src');
				image.full = $(this).attr('href');
				image.title = $(this).children('img').attr('alt');
				img.push(image);
			});
			images = img;
		} else {
			modal.isContent = true;
			ajaxLink = $(this).attr('href');
		}
		createStructure();
		return this;
	};
	
	$.fn.PwModal.settings = {};
	
	function init()
	{	
		
		if (isIE6) {
			$body.css({
				height: $body.height()+'px',
				width: $body.width()+'px',
				position: 'static',
				overflow: 'hidden'
			});
			$('html').css({overflow: 'hidden'});
		}
		
		modal = {
			srtucture: {}, // структура окна
			ready: false, // false - окно не создано, true - окно создано
			isGallery: false, // false - контент, true - галерея
			isContent: false
		}
		
		$.fn.PwModal.settings = {
			startWidth: 300, //стартовая ширина
			startHeight: 300, //стартовая высота
			defaultWidth: 500,
			defaultHeight: 500,
			galleryHeight: (125/* + 36*/), //высота блока #pwModalThumb
			indent: 25 //отступ от края окна
		}
		
	}
	
	function createStructure()
	{
		if (modal.ready) {
			return;
		}
		$body.append(
			$(
				'<div id="pwModalFull">' + 
					'<div id="pwModalBg" />' +  
					'<div id="pwModalWindow">' +
						'<div class="cTop"><i><!-- --></i></div>' + 
						'<div class="fixbg-l">' + 
							'<div class="fixbg-r">' +
								'<a title="Предыдущая" id="pwModalPrev" href="#" title="Предыдущая">&nbsp;</a>' + 
								'<a title="Следующая" id="pwModalNext" href="#" title="Следующая">&nbsp;</a>' + 
								'<div id="pwModalThumb">' + 
									//'<h1>Фотографии объекта</h1>' + 
									'<div class="photos-i">' + 
										'<div class="photos-inner" />' + 
									'</div>' + 
								'</div>' + 
								'<div id="pwModalContent">' + 
									'<div id="pwModalLoading" />' +  
									//'<a title="Предыдущая" id="pwModalPrev" href="#">Предыдущая</a>' + 
									//'<a title="Следующая" id="pwModalNext" href="#">Следующая</a>' + 
								'</div>' +
								'<a id="pwModalClose" title="Закрыть (Esc)" href="#">Закрыть (Esc)<i><!-- --></i></a>' + 
								'<div id="pwModalTitle"><span>&nbsp;</span></div>' +
							'</div>' + 	 
						'</div>' + 
						'<div class="cBtm"><i><!-- --></i></div>' + 
					'</div>' + 
				'</div>'
			).hide()
		);
		modal.structure = {
			full: $('#pwModalFull'),
			bg: $('#pwModalBg'),
			window: $('#pwModalWindow'),
			thumb: $('#pwModalThumb'),
			content: $('#pwModalContent'),
			loading: $('#pwModalLoading'),
			title: $('#pwModalTitle span'),
			next: $('#pwModalNext'),
			prev: $('#pwModalPrev'),
			close: $('#pwModalClose')
		};

		$(modal.structure.bg).css("opacity", "0.2");

		if (modal.isGallery) {
			
			for (i in images) {
				var img = images[i];
				$('.photos-inner', modal.structure.thumb)
					.append('<a href="' + img.full + '"><img src="' + img.preview + '" alt="' + img.title + '" /><i><!-- --></i></a>');

			}
			$('.photos-inner', modal.structure.thumb).width(images.length*80);
			$('a', modal.structure.thumb).click(setImage);
			
		} else {
			modal.structure.thumb.remove();
			modal.structure.prev.remove();
			modal.structure.next.remove();
			modal.structure.title.parents(':first').remove();
			$.fn.PwModal.settings.galleryHeight = 0;
			
		}
		
		modal.structure.window.hide();
		
		modal.ready = true;
		
		calcSize = calculateSize($.fn.PwModal.settings.startWidth, $.fn.PwModal.settings.startHeight);
		modal.structure.content
			.css({
				width: calcSize.width + 'px',
				height: calcSize.height + 'px'
			});

		if (modal.isGallery) {
			$('.photos-i', modal.structure.thumb)
				.animate({
					width: calcSize.imgW - 40,
					scrollLeft: ((((activeImage + 1) * 60)- 40) - Math.round(calcSize.imgW / 2))
				}, animateSpeed);
			
			modal.structure.title
				.animate({
					width: calcSize.imgW
				}, animateSpeed); 
		}
		
		modal.structure.window
			.css({
				width: (calcSize.width) + 'px',
				top: calcSize.top,
				left: calcSize.left
			})
			.show();
		
		modal.structure.full.fadeIn(300, function() {
			$(document).keyup(function(event){
			    if (event.keyCode == 27) {
			    	destruct();
			    }
			});
		});

		load();
		
		if (modal.isGallery) {

			$("#pwModalPrev2").click(function() {
				$(modal.structure.prev).trigger('click');
			});

			$("#pwModalNext2").click(function() {
				$(modal.structure.next).trigger('click');
			});

			modal.structure.next
				.click(function(){
					if (activeImage >= images.length - 1) {
						activeImage = -1; 
					}
					activeImage++;
					showLoadingAndLoad();
					return false;
				});
			

			modal.structure.prev
				.click(function(){
					if (activeImage <= 0) {
						activeImage = images.length; 
					}
					activeImage--;
					showLoadingAndLoad();
					return false;
				});
		}
		
		$(modal.structure.close).click(destruct);
		
		$(modal.structure.bg).click(destruct);
		
	}
	
	function destruct()
	{
		$(modal.structure.window).fadeOut(300, function(){
			
			if (isIE6) {
				$body.css({height: '', width: '', position: '', overflow: ''});
				$('html').css({overflow: ''});
			}
			
			$(modal.structure.full).remove();
			$(document).unbind('keyup');
		});
		return false;
	}
	
	function load()
	{
		if (modal.isContent) {
			loadContent();
		} else {
			selectImage();
			loadImage();
		}
	}
	
	function loadContent()
	{
		var queryString = ajaxLink.replace(/^[^\?]+\??/,'');
		var params = parseQuery(queryString);
		
		var modalWidth = params['width'] ? parseInt(params['width']) : $.fn.PwModal.settings.defaultWidth;
		var modalHeight = params['height'] ? parseInt(params['height']) : $.fn.PwModal.settings.defaultHeight;
		//console.log(modalHeight);

		if (params['height'] == 'auto') {
			modalHeight = $(window).height() - ($.fn.PwModal.settings.indent * 2);
		}
		
		var modalTop = calculateTop(modalHeight);
		var modalLeft = calculateLeft(modalWidth);
		
		$.get(
			ajaxLink,
			{},
			function(response) {
				modal.structure.window
					.animate({
						width: modalWidth,
						height: modalHeight,
						top: modalTop,
						left: modalLeft
					}, animateSpeed); 
			
				modal.structure.content
					.append(response)
					.animate({
						width: modalWidth,
						height: modalHeight
					}, animateSpeed, function(){
						modal.structure.loading.fadeOut();
						$(element).trigger('thickboxAjaxAfterLoad');
					});
				
			}
		);
	}
	
	function loadImage()
	{
		var loadImg = new Image();
		loadImg.onload = function() {
			loadImg.onload = null;

			modal.structure.title.html('&nbsp;');
			$('img', modal.structure.content)
				.fadeOut(animateSpeed, function(){
					$(this).remove();
				});
			
			calcSize = calculateSize(loadImg.width, loadImg.height);
			loadImg.width = calcSize.imgW;
			loadImg.height = calcSize.imgH;
			
			loadImg.alt = images[activeImage].title;
			
			modal.structure.window
				.animate({
					width: calcSize.width,
					height: (calcSize.height + $.fn.PwModal.settings.galleryHeight + modal.structure.title.height()),
					top: calcSize.top,
					left: calcSize.left
				}, animateSpeed); 
			
			$('.photos-i', modal.structure.thumb)
				.animate({
					width: calcSize.imgW - 40,
					scrollLeft: ((((activeImage + 1) * 60) - 40) - Math.round(calcSize.imgW / 2))
				}, animateSpeed);
			
			modal.structure.title
				.animate({
					width: calcSize.imgW
				}, animateSpeed); 
			
			modal.structure.content
				.animate({
					width: calcSize.width,
					height: calcSize.height
				}, animateSpeed, function(){

					$(this).append(loadImg);
					
					if (loadImg.alt) {
						modal.structure.title
							.html(loadImg.alt)
							.show();
					} else {
						modal.structure.title.html('&nbsp;');
					}
					modal.structure.loading.fadeOut(animateSpeed);
					$(element).trigger('thickboxAjaxAfterLoad');
				});
		}
		loadImg.src = images[activeImage].full;
	}
	
	function setImage()
	{
		var list = $('a', modal.structure.thumb);
		activeImage = list.index(this);		
		showLoadingAndLoad();
		return false;
	}
	
	function selectImage()
	{
		var list = modal.structure.thumb.find('a');
		list.removeClass('actived');
		list.eq(activeImage).addClass('actived');
	}
	
	function showLoadingAndLoad()
	{
		selectImage();
		modal.structure.loading.fadeIn(600, function(){
			loadImage();
		});
	}
	
	function calculateSize(imageWidth, imageHeight)
	{
		//вычисляем максимальную высоту и ширину контента для текущего размера окна
		var maxContentWidth = $(window).width() - ($.fn.PwModal.settings.indent * 2); // минус отступы от краев;
		var maxContentHeight = $(window).height() - ($.fn.PwModal.settings.indent * 2) - 50 ; // минус отступы от краев и тени;

		//вычитаем высоту блока для комментария
		maxContentHeight -= modal.structure.title.height();

		var calcSize = {		
			top: 0, //отступ от верхнего края окна
			left: 0, //отступ от левого края окна
			width: 0, //ширина блока content
			height: 0, //высота блока content
			imgW: 0,  //ширина изображения
			imgH: 0 //высота изображения
		}
		
		//ширина навигационных ссылок prev и next
		var navLinkWidth = 60 * 2;
		
		//если это галерея
		if (modal.isGallery) {
			maxContentWidth -= navLinkWidth; //вычитаем ширину ссылок next и prev
			maxContentHeight -= $.fn.PwModal.settings.galleryHeight; //вычитаем высоту блока с preview
		}		
		
		//вычисляем размеры изображения
		if (imageWidth > maxContentWidth && imageHeight < maxContentHeight) {
			calcSize.imgW = maxContentWidth;
			calcSize.imgH = Math.round((calcSize.imgW * imageHeight) / imageWidth);
		}
		
		if (imageWidth < maxContentWidth && imageHeight > maxContentHeight) {
			calcSize.imgH = maxContentHeight;
			calcSize.imgW = Math.round((imageWidth * calcSize.imgH) / imageHeight);
		}
		
		if (imageWidth < maxContentWidth && imageHeight < maxContentHeight) {
			calcSize.imgW = imageWidth;
			calcSize.imgH = imageHeight;
		}

		if (imageWidth > maxContentWidth && imageHeight > maxContentHeight) {
			if (maxContentWidth < maxContentHeight) {
				calcSize.imgW = maxContentWidth;
				calcSize.imgH = Math.round((calcSize.imgW * imageHeight) / imageWidth);
			}
			else {
				calcSize.imgH = maxContentHeight;
				calcSize.imgW = Math.round((imageWidth * calcSize.imgH) / imageHeight);
			}
		}
		
		//вычисляем размеры блока content
		calcSize.width = calcSize.imgW + navLinkWidth;
		calcSize.height = calcSize.imgH + 50;
		
		//вычисляем отступы от краев окна
		var tmpImgHeight = calcSize.height;
		if (modal.isGallery) {
			tmpImgHeight += $.fn.PwModal.settings.galleryHeight;
		}
		tmpImgHeight += modal.structure.title.height();
		
		calcSize.top = calculateTop(tmpImgHeight);
		calcSize.left = calculateLeft(calcSize.width);
		//console.log(calcSize.width);
		return calcSize;
	}
	
	function calculateTop(height)
	{
		var extraHeight = 0;
		if (isIE6) {
			extraHeight = $(window).scrollTop();
		}
		return Math.round((($(window).height() - height) / 2) + extraHeight) - 9;
	}
	
	function calculateLeft(width)
	{
		var extraWidth = 0;
		if (isIE6) {
			extraWidth = $(window).scrollLeft();
		}
		return Math.round((($(window).width() - width) / 2) + extraWidth) - 9;
	}
	
	function parseQuery (query) {
	   var params = {};
	   if (!query) {return params;}// return empty object
	   var pairs = query.split(/[;&]/);
	   for (var i = 0; i < pairs.length; i++) {
	      var keyVal = pairs[i].split('=');
	      if (!keyVal || keyVal.length != 2 ) { continue; }
	      var key = unescape( keyVal[0] );
	      var val = unescape( keyVal[1] );
	      val = val.replace(/\+/g, ' ');
	      params[key] = val;
	   }

	   return params;
	}
});

$(function(){
	$('.PwModal').click(function(){
		$(this).PwModal();
		return false;
	});
	$('.PwModal2').click(function(){
		$(this).PwModal();
		return false;
	});
	$('.PwModal3').click(function(){
		$(this).PwModal();
		return false;
	});
});
