jQuery(function($) 
{
	var $body = $('body');
	var vis_hide = {visibility:"hidden"};
	var vis_show = {visibility:"visible"};
	var structureModal = {};
	var modal = {};
	var images;
	var ajaxLink;
	var curHeight;
	var linkTitle;
	var linkText;
	var activeImage;
	var animateSpeed = 200;
	var element;
	var galleryMode = 'page';
	var nextID;
	var prevID;
	var ajaxPhotoInfo;
	var section = -1;

	var showInfo    = false;
	var maxRating   = 5;
	var infoURL;
	var IDPhotoArgument = 'photo';
	
	//INTERNRT EXPLORER 6
	var isIE6 = false;
	if (window.external && (typeof window.XMLHttpRequest == "undefined")) {
		isIE6 = true;
	}
	
	$.fn.OozeGallery = function(settings)
	{
		if (!this)
			return false;

		if (settings != undefined)
		{
			if (settings.GalleryMode != undefined)
				galleryMode = settings.GalleryMode;

			if (settings.AnimateSpeed != undefined)
				animateSpeed = settings.AnimateSpeed;

			if (settings.ShowInfo != undefined)
				showInfo = settings.ShowInfo;

			if (settings.MaxRating != undefined)
				maxRating = settings.MaxRating;

			if (settings.InfoURL != undefined)
				infoURL = settings.InfoURL;

			if (settings.IDPhotoArgument != undefined)
				IDPhotoArgument = settings.IDPhotoArgument;
		}		
	
		element   = this;

		init();

		linkTitle = $(this).attr('title') ? $(this).attr('title') : "";
		linkText  = $(this).text() ? $(this).text() : "";

		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.id       = $(this).attr('photo_id') ? $(this).attr('photo_id') : 0;
				image.section  = $(this).attr('section') ? $(this).attr('section') : -1;
				image.preview  = $(this).children('img').attr('src');
				image.full     = $(this).attr('href');
				image.title    = $(this).children('img').attr('alt');
				img.push(image);
			});
			images = img;
			section = images[activeImage].section;
		}
		else
		{
			modal.isContent = true;
			ajaxLink = $(this).attr('href');
		}
		createStructure();
		return this;
	}
	
	$.fn.OozeGallery.settings = {};
	
	function init()
	{
		if (isIE6) 
		{
			$("select").css(vis_hide);
			$body.css({
				height   : $body.height()+'px',
				width    : $body.width()+'px',
				position : 'static',
				overflow : 'hidden'
			});
			$('html').css({overflow: 'hidden'});
		}
		
		modal = 
		{
			srtucture       : {},
			ready           : false,
			isGallery       : false,
			isContent       : false
		}
		
		$.fn.OozeGallery.settings = 
		{
			startWidth      : 480,
			startHeight     : 480,
			defaultWidth    : 500,
			defaultHeight   : 500,
			galleryHeight   : (140/* + 36*/),
			indent          : 10
		}
	}
	
	function createStructure()
	{
		if (modal.ready)
			return;

		$body.append
		(
			$(
				'<div id="galleryModalFull">' +
					'<div id="galleryModalBg" />' +
					'<div id="galleryModalWindow">' +
						'<div id="galleryModalThumb">' +
							'<h1>Фотографии</h1>' +
							'<div class="photos-i">' +
								'<div class="photos-inner" />' +
							'</div>' +
						'</div>' +
						'<div id="galleryModalTitle">&nbsp;</div>' +
						'<div id="galleryModalContent">' +
							'<div id="galleryModalLoading" />' +
							'<a title="Предыдущая" id="galleryModalPrev" href="#"><!-- --></a>' +
							'<a title="Следующая" id="galleryModalNext" href="#"><!-- --></a>' +
						'</div>' +
						'<div id="galleryModalInfo">'+
							'<div id="galleryModalRatingTitle">Оценка:</div>'+
							'<div id="galleryModalRating">'+
							  '<input name="star1" type="radio" class="star"/>'+
							  '<input name="star1" type="radio" class="star"/>'+
							  '<input name="star1" type="radio" class="star"/>'+
							  '<input name="star1" type="radio" class="star"/>'+
							  '<input name="star1" type="radio" class="star"/>'+
							'</div>'+
							'<div id="galleryModalHits">0</div>'+
							'<div id="galleryModalHitsTitle">Просмотров:</div>'+
						'</div>' +
						'<a id="galleryModalClose" title="Закрыть (Esc)" href="#">Закрыть (Esc)<i><!-- --></i></a>' +
					'</div>' +
				'</div>'
			).hide()
		);
		modal.structure = 
		{
			full          : $('#galleryModalFull'),
			bg            : $('#galleryModalBg'),
			window        : $('#galleryModalWindow'),
			thumb         : $('#galleryModalThumb'),
			content       : $('#galleryModalContent'),
			loading       : $('#galleryModalLoading'),
			title         : $('#galleryModalTitle'),
			next          : $('#galleryModalNext'),
			prev          : $('#galleryModalPrev'),
			close         : $('#galleryModalClose'),
			info          : $('#galleryModalInfo'),
			rating_title  : $('#galleryModalRatingTitle'),
			rating        : $('#galleryModalRating'),
			hits_title    : $('#galleryModalHitsTitle'),
			hits          : $('#galleryModalHits')
		};

		if (modal.isGallery) 
		{
			modal.structure.thumb.remove();
			if (showInfo)
			{
				modal.structure.rating.hide()
				modal.structure.rating_title.hide();
				modal.structure.hits.hide()
				modal.structure.hits_title.hide();
			}
			else
				modal.structure.info.remove();
				
			$.fn.OozeGallery.settings.galleryHeight = 0;
		} 
		else 
		{
			if (modal.isContent)
				modal.structure.title.remove();

			modal.structure.thumb.remove();
			modal.structure.info.remove();
			modal.structure.prev.remove();
			modal.structure.next.remove();
			$.fn.OozeGallery.settings.galleryHeight = 0;
		}

		modal.structure.window.hide();
		modal.ready = true;

		calcSize = calculateSize($.fn.OozeGallery.settings.startWidth, $.fn.OozeGallery.settings.startHeight);
		modal.structure.content.css(
		{
			width  : calcSize.width + 'px',
			height : calcSize.height + 'px'
		});

		modal.structure.window.css(
		{
			width : (calcSize.width + 18) + 'px',
			top   : calcSize.top + 'px',
			left  : calcSize.left + 'px'
		}).show();

		modal.structure.full.fadeIn(300, function() 
		{
			$(document).keyup(function(event)
			{
			    if (event.keyCode == 27)
			    	destruct();
			});
		});

		load();
		
		if (modal.isGallery) 
		{
			modal.structure.next.click(function()
			{
				if (galleryMode == 'AJAX')
					showLoadingAndLoad(nextID);
				else
				{
					if (activeImage >= images.length - 1)
						activeImage = -1;

					activeImage++;
					showLoadingAndLoad(-1);
				}
				return false;
			});

			modal.structure.prev.click(function()
			{
				if (galleryMode == 'AJAX')
					showLoadingAndLoad(prevID);
				else
				{
					if (activeImage <= 0)
						activeImage = images.length;

					activeImage--;
					showLoadingAndLoad(-1);
				}
				return false;
			});
		}

		$(modal.structure.close).click(destruct);
		$(modal.structure.bg).click(destruct);		
	}

	function CreateRatingBlock(current_rating)
	{
		var rating = '';
		for(var i = 0; i < maxRating; i++)
			if  (i === (current_rating -1))
				rating += '<input name="star1" value="'+(i+1)+'" type="radio" class="star" checked="checked" />';
			else
				rating += '<input name="star1" value="'+(i+1)+'" type="radio" class="star" />';

		modal.structure.rating_title.show();
		modal.structure.rating.hide().empty().append(rating).show();;
		$('input[type=radio].star').rating();
	}

	function GetPhotoInfo(id)
	{
		if (id <= 0)
			id = images[activeImage].id;

		$.getJSON(
					'http://'+window.location.hostname+infoURL+'?section='+section+'&'+IDPhotoArgument+'='+id+'&t='+(new Date).getTime(),
					{},
					function(json)
					{
						//alert('section: '+ json.NodeID +', id: ' + json.id + ', hits: ' + json.hits + ', mark: '+json.mark + ', rating: ' + json.rating);
						ajaxPhotoInfo = json; 
						CreateRatingBlock(json.rating);
						modal.structure.hits_title.show();
						modal.structure.hits.hide().empty().append(json.hits).show();
						if (json.navigatin.next != undefined && json.navigatin.next.ID != undefined)
						{
							nextID = json.navigatin.next.ID;
							modal.structure.next.show();
						}
						else
						{
							modal.structure.next.hide();
							nextID = -1;
						}

						if (json.navigatin.prev != undefined && json.navigatin.prev.ID != undefined)
						{
							prevID = json.navigatin.prev.ID;
							modal.structure.prev.show();
						}
						else
						{
							modal.structure.prev.hide();
							prevID = -1;
						}
						loadImage(id);
					}
				);
	}

	function destruct()
	{
		$(modal.structure.window).fadeOut(300, function()
		{
			if (isIE6) 
			{
				$body.css({height: '', width: '', position: '', overflow: ''});
				$('html').css({overflow: ''});
				$("select").css(vis_show);
			}

			$(modal.structure.full).remove();
			$(document).unbind('keyup');
			clearTimeout(window.autoClose);
		});
		return false;
	}

	function load()
	{
		if (modal.isContent)
			loadContent();
		else 
		{
			if (galleryMode == 'AJAX')
				GetPhotoInfo(images[activeImage].id);
			else
			{
				if (showInfo)
					GetPhotoInfo(images[activeImage].id)

				selectImage();
				loadImage(-1);
			}
		}
	}

	function loadContent()
	{
		var queryString = ajaxLink.replace(/^[^\?]+\??/,'');
		var params      = parseQuery(queryString);

		var modalWidth  = params['width']  ? parseInt(params['width'])  : $.fn.OozeGallery.settings.defaultWidth;
		var modalHeight = params['height'] ? parseInt(params['height']) : $.fn.OozeGallery.settings.defaultHeight;
		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('OozeGalleryAfterLoad');
								}
							);
				}
			);
	}

	function loadImage(id)
	{
		modal.structure.title.html('&nbsp;');

		var loadImg = new Image();

		/*if (showInfo)
			GetPhotoInfo(id);*/

		loadImg.onload = function() 
		{
			loadImg.onload = null;
			$('img', modal.structure.content).remove();
			calcSize       = calculateSize(loadImg.width, loadImg.height);
			loadImg.width  = calcSize.imgW;
			loadImg.height = calcSize.imgH;
			if (galleryMode == 'AJAX')
				loadImg.alt    = ajaxPhotoInfo.title;
			else
				loadImg.alt    = images[activeImage].title ? images[activeImage].title : linkText;

			if (loadImg.alt)
			{
				modal.structure.title
				.html("<strong>" + loadImg.alt + "</strong><br />")
				.show();
				
				if(linkTitle)
					modal.structure.title
					.append("<span>" + linkTitle + "</span>");
			}
			else
				modal.structure.title.html('&nbsp;');

			if (showInfo)
			{
				modal.structure.window
				.animate(
							{
								width  : calcSize.width,
								height : (calcSize.height + $.fn.OozeGallery.settings.galleryHeight + 12 + modal.structure.title.height() + 12 + modal.structure.info.height()),
								top    : calcSize.top,
								left   : calcSize.left
							},
							animateSpeed
						);
			}
			else
			{
				modal.structure.window
				.animate(
							{
								width  : calcSize.width,
								height : (calcSize.height + $.fn.OozeGallery.settings.galleryHeight + 12 + modal.structure.title.height()),
								top    : calcSize.top,
								left   : calcSize.left
							},
							animateSpeed
						);
			}

			$('.photos-i', modal.structure.thumb)
			.animate(
						{
							width       : calcSize.imgW,
							scrollLeft  : ((((activeImage + 1) * 80) - 40) - Math.round(calcSize.imgW / 2))
						},
						animateSpeed
					);

			modal.structure.content
			.animate(
						{
							width  : calcSize.width,
							height : calcSize.height
						},
						animateSpeed,
						function()
						{
							$(this).append(loadImg);
							modal.structure.loading.fadeOut(animateSpeed);
							$(element).trigger('OozeGalleryAfterLoad');
						}
					);
		}
		if (galleryMode == 'AJAX')
			loadImg.src = ajaxPhotoInfo.full;
		else
			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(id)
	{
		selectImage();
		modal.structure.loading.fadeIn(
											600,
											function()
											{
												if (galleryMode == 'AJAX' || showInfo)
													GetPhotoInfo(id);
												//loadImage(id);
											}
										);
	}

	function calculateSize(imageWidth, imageHeight)
	{
		var windowWidth  = $(window).width()  - ($.fn.OozeGallery.settings.indent * 2);
		var windowHeight = $(window).height() - ($.fn.OozeGallery.settings.indent * 2);

		windowHeight    -= modal.structure.title.height();

		//alert(modal.structure.info.innerHeight());
		if (modal.isGallery && showInfo)
			windowHeight    -= (modal.structure.info.innerHeight()+12);
		//console.log('titleHeight: ' + modal.structure.title.height());

		var calcSize = 
		{
			top    : 0,
			left   : 0,
			width  : 0,
			height : 0,
			imgW   : 0,
			imgH   : 0,
			scroll : 0
		}

		var navLinkWidth = 0;

		/*if (modal.isGallery) {
			windowHeight -= $.fn.OozeGallery.settings.galleryHeight;
			//console.log('galleryHeight: ' + $.fn.OozeGallery.settings.galleryHeight);
		}*/

		//console.log('window(w,h): ' + windowWidth + ', ' + windowHeight);


		if (imageWidth > windowWidth && imageHeight < windowHeight) 
		{
			calcSize.width  = windowWidth;
			calcSize.height = Math.round((calcSize.width * imageHeight) / imageWidth);
		}

		if (imageWidth < windowWidth && imageHeight > windowHeight) 
		{
			calcSize.height = windowHeight;
			calcSize.width  = Math.round((imageWidth * calcSize.height) / imageHeight);
		}

		if (imageWidth < windowWidth && imageHeight < windowHeight) 
		{
			calcSize.width  = imageWidth;
			calcSize.height = imageHeight;
		}

		if (imageWidth > windowWidth && imageHeight > windowHeight) 
		{
			if ((windowWidth - imageWidth) < (windowHeight - imageHeight))
			{
				calcSize.width  = windowWidth;
				calcSize.height = Math.round((calcSize.width * imageHeight) / imageWidth);
			}
			else 
			{
				calcSize.height = windowHeight;
				calcSize.width  = Math.round((imageWidth * calcSize.height) / imageHeight);
			}
		}

		calcSize.imgH    = Math.round(((calcSize.width - navLinkWidth) * calcSize.height) / calcSize.width);
		calcSize.imgW    = calcSize.width - navLinkWidth;

		calcSize.height  = calcSize.imgH;

		var tmpImgHeight = calcSize.height;
		/*if (modal.isGallery) {
			tmpImgHeight += $.fn.OozeGallery.settings.galleryHeight;
		}*/
		if (showInfo)
			tmpImgHeight    += modal.structure.title.height() + 36;
		else
			tmpImgHeight    += modal.structure.title.height() + 18;

		calcSize.top     = calculateTop(tmpImgHeight);
		calcSize.left    = calculateLeft(calcSize.width);
		return calcSize;
	}

	function calculateTop(height)
	{
		var extraHeight = 0;
		if (isIE6)
			extraHeight = $(window).scrollTop();
		if (typeof window.innerWidth != 'undefined')
			curHeight = window.innerHeight;
		else 
		{

			if (
					typeof document.documentElement != 'undefined' &&
					typeof document.documentElement.clientWidth != 'undefined' &&
					document.documentElement.clientWidth != 0
				) 
			{
				curHeight = document.documentElement.clientHeight;
			}
			else
				curHeight = $(window).height()

		}
		return Math.round(((curHeight - 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;
	}
});

$(document).ready(function()
{
	$('.OozeGallery').click(function()
	{
		$(this).OozeGallery({GalleryMode: "AJAX", ShowInfo: false, InfoURL : '/photos/photo-info'});
		return false;
	});
});
