$(document).ready(function(){
	initGallery(".main-gallery", true);
	popUp();
});



function initGallery(holder, _autoplay)
{
	var duration = 7000;
	var gallery;
	var timer;
	var autoplay = _autoplay;
	
	gallery = $(holder).find("ul.gallery li");
	gallery.number = $(gallery).length;
	if(gallery.number > 1)
	{
		gallery.current = 0;
		gallery.thumbnails = $(holder).find(".paginator li a");
		
		$(gallery).css({"opacity": 0, "display": "none"});
		$(gallery).eq(0).css({"opacity": 1, "display": "block"});

		$(holder).find(".play").click(function(){autoplay = true;rotate();return false;});
		
		$(holder).find(".pause").click(function()
		{
			if(autoplay)
			{
				autoplay = false;
				clearTimeout(timer);
			}
			else
			{
				autoplay = true;
				timer = setTimeout(function()
				{
					rotate();
				}
				, duration);
			}
			return false;
		});
		
		$(gallery.thumbnails).each(function(i, el)
		{
			$(el).click(function()
			{
    				if(gallery.current != i)
				{
					var temp = gallery.current;
					$(gallery.thumbnails).removeClass("active");
					$(el).addClass("active");
					
					$(gallery).eq(temp).animate({"opacity": 0}, 700, function() {  $(gallery).eq(temp).css({"display": "none"});  });
					$(gallery).eq(i).css({"display": "block"}).animate({"opacity": 1}, 700);
					
					clearTimeout(timer);
					
					gallery.current = i;
					
					timer = setTimeout(function()
					{
						rotate();
					}
					, duration);
				}
				return false;
			});
		});
		
		if(autoplay)
		{
			timer = setTimeout(function()
			{
				rotate();
			}
			, duration);
		}
	}
	function play()
	{
		var temp = gallery.current;
		$(gallery).eq(temp).animate({"opacity": 0}, 700, function() {  $(gallery).eq(temp).css({"display": "none"});  });
		
		if(++gallery.current >= gallery.number)
			gallery.current = 0;

		$(gallery.thumbnails).removeClass("active");
		$(gallery.thumbnails).eq(gallery.current).addClass("active");
		
		
		$(gallery).eq(gallery.current).css({"display": "block"}).animate({"opacity": 1}, 700);
		
		clearTimeout(timer); 
	}
	function rotate()
	{
		if(autoplay)
		{
			play();
			timer = setTimeout(function()
			{
				rotate();
			}
			, duration);
		}
	}
}



function popUp(){
	$('a.open').click(function(){
		_el = $(this).parent().find('.popup');
		_el.css('display','block');
		return false;
	});
	$('.close a').click(function(){
		_el = $(this).parent().parent().parent();
		_el.css('display','none');
		return false;
	});
}
