
/**
 * Фотогалерея
 * @param {String|jQuery} cont Контейнер где лежат фотографии.
 */
function popupBlock (cont){
	this.CLASS_CENTER = 'center_window';
	this.CLASS_LEFT = 'left_window';
	this.CLASS_RIGHT = 'right_window';
	this.CLASS_CURRENT = 'current';
	this.CLASS_ITEM = 'gall_item';
	this.ID_POPUP = 'popup_cont';

	this.isBusy = false;
	this.shown = false;
	
	this.popupCont = $('#' + this.ID_POPUP);
	this.shader = $('#shader');
	this.closer = $('#closer');
	this.popupBlock = $("." + this.CLASS_CENTER);
	this.leftBlock = $("." + this.CLASS_LEFT);
	this.rightBlock = $("." + this.CLASS_RIGHT);


	var that = this;

	this.images = $('.img_link' , $(cont)[0]);
	// двусвязный список всех "фотографий" данной галереи, чтобы избавиться от поиска по dom в дальнейшем
	this.images.each(function(ix){
		this.prev_item = (ix - 1 < 0) ? null : that.images[ix - 1];
		this.next_item = (ix + 1 == that.images.length) ? null : that.images[ix + 1];
	});

	this.updateDimensions();

	this.popupBlock.css({
		visibility : "hidden",
		display : "block"
	});

	this.tmpImg = new Image();
	$(this.tmpImg).load(function(){
		that.newWidth();
	});

	this.attachEvents();
};

popupBlock.prototype = {
	/**
	 * Задаем размер контейнера 
	**/
	updateDimensions : function(){
		this.windowWidth = $(window).width();
		this.windowHeight = $(document).height();
		
		this.popupCont.width(this.windowWidth).height(this.windowHeight);
		this.shader.width(this.windowWidth).height(this.windowHeight);
	},
	/**
	 * Показываем картинку и необходимую анимацию
	 * @param {Element} img Картинка, которую показываем
	 * @param {String} prev Куда нажали(право, лево)
	 */
	showImage : function(img, prev){
		var that = this;
		/**
		 * Нажали на левое изображение
		 */
		var center, right, left, centerWidth, leftWidth, rightWidth;

		that.popupCont.show();
		that.windowTop = window.pageYOffset || document.documentElement.scrollTop;
		that.closer.css({top: that.windowTop+30}).show();

		if(prev === 'left'){
			if (!this.shown) return true;
			center = this.popupBlock;
			right = this.rightBlock;
			left = this.leftBlock;
			center.unbind("click");

			centerWidth = this.imgWidth;
			leftWidth = this.leftImage;

			this.popupBlock.css(
				{
					left: (this.windowWidth - this.imgWidth)/2 - 10,
					marginLeft: 0
				}
			);

			this.leftBlock.css(
				{
					right: "auto",
					marginRight: 0
				}
			);

			$(this.currentImage).removeClass(this.CLASS_CURRENT);
			$(this.currentImage[0].prev_item).addClass(this.CLASS_CURRENT);
			this.currentImage = (this.currentImage[0].prev_item != null) ? $(this.currentImage[0].prev_item) : this.currentImage;
			this.prevItem = this.currentImage[0].prev_item;
			this.nextItem = this.currentImage[0].next_item;

			this.popupBlock.animate(
				{
					left: this.windowWidth-100,
					marginLeft: 0
				}, 500, function(){
					center.removeClass(that.CLASS_CENTER).addClass(that.CLASS_RIGHT);
					that.rightBlock = center;
					that.rightImage = centerWidth;
				}
			);

			this.leftBlock.animate(
				{
					// magic number 10 - ширина рамки блока с картинкой
					left: (this.windowWidth - this.leftImage)/2 - 10
				}, 500, function(){
					left.removeClass(that.CLASS_LEFT).addClass(that.CLASS_CENTER);
					that.popupBlock = left;
					that.imgWidth = leftWidth;
				}
			);

			right.remove();
			this.leftBlock = $("<div class='gall_item left_window'><\/div>").appendTo(this.popupCont);
			if(this.prevItem != null){
				var leftImg = new Image();
				leftImg.onload = function(){
						that.leftPreview(leftImg);
					};
				leftImg.src = $(this.prevItem).attr("href");
			}
			else{
				setTimeout(
					function(){
						that.isBusy = false;
					}, 250
				);
			}
		}
		/**
		 * Нажали на правое изображение
		 */
		else if(prev === 'right'){
		    if (!this.shown) return true;
		    center = this.popupBlock;
            right = this.rightBlock;
            left = this.leftBlock;
    		center.unbind("click");
			centerWidth = this.imgWidth;
			rightWidth = this.rightImage;

			this.rightBlock.css(
				{
					left: this.windowWidth-100,
					marginLeft: 0
				}
			);

			this.popupBlock.css(
				{
					left: (this.windowWidth - this.imgWidth)/2 - 10,
					marginLeft: 0
				}
			);

            $(this.currentImage).removeClass(this.CLASS_CURRENT);
			$(this.currentImage[0].next_item).addClass(this.CLASS_CURRENT);



			this.currentImage = (this.currentImage[0].next_item != null) ? $(this.currentImage[0].next_item) : this.currentImage;
			this.prevItem = this.currentImage[0].prev_item;
            this.nextItem = this.currentImage[0].next_item;



			this.popupBlock.animate(
				{
					left: -(this.imgWidth-80),
					marginLeft: 0
				}, 500, function(){
					center.removeClass(that.CLASS_CENTER).addClass(that.CLASS_LEFT);
					that.leftBlock = center;
					that.leftImage = centerWidth;
				}
			);

			this.rightBlock.animate(
				{
					// magic number 10 - ширина рамки блока с картинкой
					left: (this.windowWidth - this.rightImage)/2 - 10
				}, 500, function(){
					right.removeClass(that.CLASS_RIGHT).addClass(that.CLASS_CENTER);
					that.popupBlock = right;
					that.imgWidth = rightWidth;
				}
			);

			left.remove();
			this.rightBlock = $("<div class='gall_item right_window'><\/div>").appendTo(this.popupCont);

			if(this.nextItem != null){
				var rightImg = new Image();
				rightImg.onload = function(){
						that.rightPreview(rightImg);
					};
				rightImg.src = $(this.nextItem).attr("href");
			}
			else{
				setTimeout(
					function(){
						that.isBusy = false;
					}, 250
				);
			}

		}
		/**
		 * Первая загрузка картинок
		 */
		else {
		    this.shown = true;
		    this.currentImage = this.images.filter("." + this.CLASS_CURRENT);
			this.prevItem = this.currentImage[0].prev_item;
			this.nextItem = this.currentImage[0].next_item;

			if(img.tagName === 'A'){
				this.tmpImg.src = $(img).attr("href");
			}
			else{
				this.tmpImg.src = $(img).attr("src");
			}
		}
	},

	/**
	 * Скрываем галерею
	 *
	 */
	hideImage : function(){
		var that = this;
		$(that.tmpImg).unbind('load');
		if (!this.shown) return true;
		this.shown = false;

		this.popupBlock.css({
			"visibility": "hidden",
			width: this.beginWidth,
			height: this.beginHeight,
			marginLeft: -75
		});

		this.tmpImg = new Image();
		$(this.tmpImg).load(function(){
			that.newWidth();
		});

		this.popupBlock.empty();
		this.leftBlock.hide().removeAttr("style").empty();
		this.rightBlock.hide().removeAttr("style").empty();
		this.images.removeClass(this.CLASS_CURRENT);
		this.popupCont.hide();
	},

	newWidth : function(){
		var that = this;

		this.popupCont = $("#" + this.ID_POPUP);
		this.popupBlock = $("." + this.CLASS_CENTER);
		this.leftBlock = $("." + this.CLASS_LEFT);
		this.rightBlock = $("." + this.CLASS_RIGHT);
		this.updateDimensions();
		this.popupCont.show();


		this.imgWidth = this.tmpImg.width;
		this.imgHeight = this.tmpImg.height;

		this.windowTop = window.pageYOffset || document.documentElement.scrollTop;
		this.windowHeight = window.innerHeight || document.documentElement.clientHeight;

		this.closer.css({top: this.windowTop+30}).show();
		var topOffset = this.windowTop + (this.windowHeight - this.imgHeight)/2;

		this.popupBlock.css({
			"visibility" : "visible",
			"display" : "block"
		});

		this.popupBlock.css(
			{
				top : topOffset,
				width: this.imgWidth,
				marginLeft: -(this.imgWidth/2 + 10),
				left: '50%'
			}
		);
		// создаем дополнительные элементы (описание, ссылки на другие страницы, оригинальный размер фотографии)
		this.popupBlock.empty();
		this.popupBlock.append(that.tmpImg);
		this.popupBlock.append("<a class='article_link' href='" + this.currentImage.find(".article_link").attr("title") + "'>" + this.currentImage.find(".article_link").text() + "<\/a>");
		this.popupBlock.append("<div class='pic_description'>" + this.currentImage.find(".pic_description").html() + "<\/div>");
		var source = this.currentImage.find(".source_img");
		if(source.length ){
			this.popupBlock.append("<div class='pic_source'>" + "<a target='_blank' href='" + $(source).attr('title') + "'>" +  $(source).text() + "<ins class='icon_24'><ins class='a'\/><\/ins><\/a>" + "<\/div>");
		}
		var t;
		if(this.prevItem != null){
			var leftImg = new Image();
			leftImg.onload = function(){
				that.leftPreview(leftImg);
			};
		 	leftImg.src = (this.prevItem.tagName === 'A') ? $(this.prevItem).attr("href") : $(this.prevItem).attr("src");
		}

		if(this.nextItem != null){
			var rightImg = new Image();
			rightImg.onload = function(){
					that.rightPreview(rightImg);
			};
			rightImg.src = (this.nextItem.tagName === 'A') ? $(this.nextItem).attr("href") : $(this.nextItem).attr("src");
		}
	},

	/**
	 * Подгрузка левого превью
	 * @param {Element} img Картинка
	 */
	leftPreview : function(img){
		var that = this;

		this.leftBlock.empty().show();
		this.leftImage = img.width;
		var topOffset = this.windowTop + (this.windowHeight - img.height)/2;
		this.leftBlock.css({
			top: topOffset,
			right: "auto",
			left: -(img.width+20),
			width: this.leftImage
		});
		this.leftBlock.append(img);
		this.leftBlock.append("<a class='article_link' href='" + $(this.prevItem).find(".article_link").attr("title") + "'>" + $(this.prevItem).find(".article_link").text() + "<\/a>");
		this.leftBlock.append("<div class='pic_description'>" + $(this.prevItem).find(".pic_description").html() + "<\/div>");
		var source = $(this.prevItem).find(".source_img");
		if(source.length ){
			this.leftBlock.append("<div class='pic_source'>" + "<a target='_blank' href='" + $(source).attr('title') + "'>" +  $(source).text() + "<ins class='icon_24'><ins class='a'\/><\/ins><\/a>" + "<\/div>");
		}

		setTimeout(function(){
			that.leftBlock.animate(
				{
					left: -(img.width-80)
				}, 250,
				function(){
					that.isBusy = false
				}
			);
		}, 250)
	},

	/**
	 * Подгрузка правого превью
	 * @param {Element} img Картинка
	 */
	rightPreview : function(img){
		var that = this;

		this.rightBlock.empty().show();
		var topOffset = this.windowTop + (this.windowHeight - img.height)/2;
		this.rightImage = img.width;

		this.rightBlock.css({
			top: topOffset,
			marginLeft: 0,
			width: this.rightImage
		});

		this.rightBlock.append(img);
		this.rightBlock.append("<a class='article_link' href='" + $(this.nextItem).find(".article_link").attr("title") + "'>" + $(this.nextItem).find(".article_link").text() + "<\/a>");
		this.rightBlock.append("<div class='pic_description'>" + $(this.nextItem).find(".pic_description").html() + "<\/div>");
		var source = $(this.nextItem).find(".source_img");
		if(source.length){
			this.rightBlock.append("<div class='pic_source'>" + "<a target='_blank' href='" + $(source).attr('title') + "'>" +  $(source).text() + "<ins class='icon_24'><ins class='a' \/><\/ins><\/a>" + "<\/div>");
		}

		setTimeout(function(){
			that.rightBlock.animate(
				{
					marginLeft: -100
				}, 250,
				function(){
					that.isBusy = false
				}
			);
		}, 250)
	},


	/**
	 * Показываем flash в центральном попапе
	 * @param {Element|jQuery} flash Элемент со ссылкой на флэш
	 */
	showFlash : function(flash){
		var that = this;

		this.popupBlock.empty();

		var flashvars = {
			video: $(flash).attr("href"),
			css: "css/default.css",
			skin: "skin/gasprom.swf",
			cover: "cover/default.jpg"
		};
		this.imgWidth = 500;
		this.imgHeight = 500;
		this.windowTop = window.pageYOffset || document.documentElement.scrollTop;
		this.windowHeight = window.innerHeight || document.documentElement.clientHeight;
		var topOffset = this.windowTop + (this.windowHeight - this.imgHeight)/2;
		this.popupBlock.css({
			"visibility" : "visible"
		});
		this.popupBlock.animate(
			{
				top : topOffset,
				width: this.imgWidth,
				height: this.imgHeight,
				marginLeft: -(this.imgWidth/2)
			}, 250,
			function(){
				$("<div id='flash_container'><\/div>").appendTo(that.popupBlock);
				swfobject.embedSWF("swf/video_player.swf", "flash_container", "500", "500", "9.0.0","expressInstall.swf",flashvars);
			}
		);
	},

	/**
	 * Подгоняем позицию попапа при ресайзе окна
	 * @param {Element|jQuery} container попап
	 */
	imgTopOffset :function(container){
		var cont = $(container);
		var img = cont.find("img")[0];
		if(img){
			switch (cont.attr("class")){
				case "gall_item center_window":
					cont.css({
						top: this.windowTop + (this.windowHeight - img.height)/2,
						marginLeft: -(img.width / 2 + 10),
						left: '50%'
					});
					break;
				case "gall_item left_window":
					cont.css({
						top: this.windowTop + (this.windowHeight - img.height)/2,
						right: "auto",
						left: -(img.width-80)
					});
					break;
				case "gall_item right_window":
					cont.css({
						top: this.windowTop + (this.windowHeight - img.height)/2,
						left: "100%",
						marginLeft: -100
					});
					break;
				default: break;
			}
		}
	},


	/**
	 * События галереи
	 *
	 */
	attachEvents : function(){
		var that = this;

		this.closer.click(
			function(){
				that.hideImage();
				if( that.popupCont.length !== 0 ){
					return false;
				}
			}
		);

		this.closer.hover(
			function(){
				that.closer.addClass("hovered");
			},
			function(){
				that.closer.removeClass("hovered");
			}
		);

		this.popupBlock.click(
			function(e){
				e.stopPropagation();
			}
		);

		$("." + this.CLASS_LEFT).live("click",
			function(e){
				if(!that.isBusy){
					that.isBusy = true;
					that.showImage($(this).find("img")[0], "left");
				}
			}
		);

		$("." + this.CLASS_RIGHT).live("click",
			function(e){
				if(!that.isBusy){
					that.isBusy = true;
					that.showImage($(this).find("img")[0], "right");
				}
			}
		);

		$(document).click(
			function(e){
				if($(e.target).parent().attr("id") == that.ID_POPUP){
					that.hideImage();
				}
			}
		);

		$(window).resize(
			function(){
				that.windowWidth = $(window).width();
				that.windowHeight = window.innerHeight || document.documentElement.clientHeight;
				that.windowTop = window.pageYOffset || document.documentElement.scrollTop;

				that.popupCont.width(that.windowWidth).height($(document).height());
				that.shader.width(that.windowWidth).height($(document).height());

				that.imgTopOffset(that.leftBlock);
				that.imgTopOffset(that.popupBlock);
				that.imgTopOffset(that.rightBlock);
			}
		);
	}
}