$(document).ready(function(){
	$(".OpenGallery").click(function(){

		var p_height;
		if($("body").height() < $(".index").height())
			p_height = $(".index").height();
		else
			p_height = $("body").height();
		$(".popupBackground").css({
			opacity:"0.8",
			height:p_height+"px"
		}).show().click(function(){
			$(".gp-close").parents(".gp-content").animate({opacity:"0"},200,function(){
				$(this).parents(".galleryPopup").animate({height:"20px"},300,"swing",function(){
					$(this).animate({width:"20px"},500,"swing",function(){
						$(this).hide();
						$(".popupBackground").hide();
					});
				});
			});
			$(".p-prev img").click();
		});
		$(".galleryPopup").show().animate({width:"714px"},500,"swing",function(){
			$(this).animate({height:"411px"},300,"swing",function(){
				$(this).children(".gp-content").css("opacity","0").show().animate({
					opacity:"1"
				},200,function(){
					var content = $(".p-gallerys"),
					item = $(".p-gallery"),
					itemHeight = 0;
					
					$.each(item,function(key,val){
						itemHeight += $(val).height()+21;
					});

					var maxVal = itemHeight - parseInt($(".gp-content").height());
					if(itemHeight >= 380)
					{
						content.css("top", "0px");
						var sliderOpts = {
							orientation: "vertical",
							value:maxVal,
							max: maxVal,
							slide: function(e, ui){
								content.css("top", "-" + (maxVal-ui.value) + "px");
							}
						};
						$(".galleryPopup .slider").slider(sliderOpts);
					}else
						$(".galleryPopup .slider").hide();
				});
			});
		});
	});
	$(".gp-close").click(function(){
		$(this).parents(".gp-content").animate({opacity:"0"},200,function(){
			$(this).parents(".galleryPopup").animate({height:"20px"},300,"swing",function(){
				$(this).animate({width:"20px"},500,"swing",function(){
					$(this).hide();
					$(".popupBackground").hide();
				});
			});
		});
		return false;
	});
	
	$(".p-prev img,.p-prev .p-close-prev").click(function(){
		$(this).parent().children("img").attr("src","#")
		.hide()
		.parents(".p-prev").css({
			opacity:"0",
			display:"none",
			width:"0px",
			height:"0px",
			left:"50%",
			top:"50%"
		});
		return false;
	});
	
	$(".p-gallery img").click(function(){
		$(".p-prev img")
			.attr("src",$(this).attr("alt"))
			.attr("alt",$(this).attr("title"))
			.attr("title",$(this).attr("title"))
			.parent().css("opacity","0").show()
				.animate({
					width:"694px",
					height:"400px",
					left:"10px",
					top:"0px",
					opacity:"1"
				},250,function(){
					$(this).children("img").show();
				});
	});
});		
