$(function() {
		$('#gallery a').click(function() {
			var url = $(this).attr('href');
			
			$.ajax({
				url: url+'?path='+ url,
				cache: false,
				success: function(data) {
					$('#album').html(data);
				}
			});

			$('#gallery a').stop().unbind('mouseover').animate({opacity: 0}, 200, function() {
				$('#gallery').hide();
				$('#album').show();
				$('#backToGallery').show();
			});
						
			return false;
		});
		
		$('#backToGallery').click(function() {
			$(this).hide();
			$('#album').hide().html('');
			$('#gallery').show();
			resizeGallery();
			$('#gallery a').animate({opacity: 1}, 200, function() {
				$(this).bind('mouseover', galleryMouseOver);
			});
			
			return false;
		});
				
		function galleryMouseOver() {
			$(this).stop().animate({
				'opacity': 0.6
			}, 50, 'easeOutQuart').animate({
				'opacity': 1
			}, 600, 'easeOutSine');
		}
		
		$('#gallery a').bind('mouseover', galleryMouseOver);
		
		
		function resizeGallery() {
			var thumbW = 250;
			var thumbH = 165;
			var boxW = 250;
			var boxH = 120;
			var defSize = 250;
			var $box = $('#gallery a');
			var winSize = $(window).width();
			
			newAlbumHeight = $(window).height() - $('#header').height();
			$('#album').height(newAlbumHeight);
			
			if ($box.length > Math.floor(winSize / defSize)) {
			
				if (winSize % defSize != 0) {
					num = Math.floor(winSize / defSize) + 1;
					size = Math.floor(winSize / num);
					$box.width(size);
					
					$box.find('img').css('left', -Math.floor((defSize-size)/2));
					//size2 = Math.floor((defSize-size)/2);
					//$box.find('img').attr('width', size + size2).css('left', -Math.floor(size2/2)).css('top', -Math.floor(((size+size2)*(thumbH/thumbW)-boxH)/2));
				
					if ((space = winSize - size * num) > 0) {
						pos = 1;
						$box.each(function() {
							if (pos > num)
								pos = 1;
							if (pos <= space)
								$(this).width($(this).width() + 1);
							pos++;
						});
					}
				}
				
			}
			else {
				$box.width(defSize);
				$box.find('img').css('left', 0);
				
				//$box.width(defSize);
				//$box.find('img').css('left', 0).attr('width', defSize);
				//$box.find('img').css('top', -Math.floor((thumbH-boxH)/2));	
			}
			
		}
		
		resizeGallery();
		$(window).resize(function() {resizeGallery();});
});