$(window).load(function () {	
	
	$('.content-gallery').each(function(){
		var album = $(this);
		var wrap = album.find('.photos-list');
		var wrapWidth = wrap.width();
		var ul = album.find('ul');
		var previous = album.find('.photo-previous');
		var next = album.find('.photo-next');
		var photos = album.find('a');
		var firstLi = $('.photos-list li').first().addClass('first');
		var lastLi = $('.photos-list li').last().addClass('last');
		
		var waitMessage = $('#waitMessage');
		var countOfPhotos = photos.length;
		var bigPhotos = [];
		var speed = 0.3;
		
		var ulWidth = 0;
		photos.each(function(i, e){
			ulWidth += $(this).outerWidth(true);
			$(this).click(function () {
				showBigPhoto($(this));
				return false;
			});
			
			bigPhotos[i] = new Image();
			bigPhotos[i].onload = function () {
				countOfPhotos--;				
			}
			bigPhotos[i].src = $(this).find('img').attr('src');
		});
		ul.width(ulWidth);
		if (ulWidth > wrapWidth) {
			next.addClass('photo-next-active');
			var minMarginLeft = wrapWidth - ulWidth + 10;
				
			next.hover(
				function() {
					var currentMarginLeft = parseInt(ul.css('margin-left'));
					previous.addClass('photo-previous-active');
					ul.animate({marginLeft : minMarginLeft}, Math.abs(currentMarginLeft - minMarginLeft) / speed, 'linear', function () {
						next.removeClass('photo-next-active');
					});
				},
				function () {
					ul.stop(true, false);
				}
			);
			
			previous.hover(
				function(){
					var currentMarginLeft = parseInt(ul.css('margin-left'));
					
					next.addClass('photo-next-active');
					
					ul.animate({marginLeft : 0}, Math.abs(currentMarginLeft) / speed, 'linear', function () {
						previous.removeClass('photo-previous-active');
					});
				},
				function () {
					ul.stop(true, false);
				}
			);
		}
		
		
		$('.top-photo, .back-photo').load(function () {
			var backPhoto = $('.back-photo');
			var topPhoto = $('.top-photo');						
			
			waitMessage.hide();
			backPhoto.css('z-index', 1).removeClass('back-photo').addClass('top-photo');
			topPhoto.css('z-index', 0).removeClass('top-photo').addClass('back-photo').fadeIn(0);
			
		});
		
		function showBigPhoto(obj) {
			waitMessage.show();
			$('.back-photo').attr('src', obj.attr('href'));
			$('.selected', album).removeClass('selected');
			obj.parent().addClass('selected');
		}
		
		function showNextPhoto() {		
			var nextLi = $('.photos-list .selected').next();
			if (nextLi.hasClass('last')) {
				firstLi.find('a').click();
			}
			else {
				nextLi.find('a').click();
			}
		}
		
	});
	
	$('.kwicks').kwicks({
		max : 448,
		spacing : 0,
		sticky : false,
		event : 'mouseover'
	});

});
