var curIndex = 0;
var isAnim = false;

$(document).ready(function(){
	$('#body div.gallery ul').each(function(){
		if( $(this).children().length > 4 ){
			var w = $(this).width();
			$(this).css('width', 1000);
			$(this).parent().prev('a').show();
			$(this).find('li:gt(3)').css('display', 'none');
			$(this).parent('div').animate({
				marginLeft: 40
			});
		}
	});
	
	$('#body div.gallery a.next_slide').click(function(){
		if( isAnim ) return false;
		
		isAnim = true;
		var div = $(this).next('div');
		var ul = div.find('ul');
		var liHidden = ul.find('li:hidden');
		var img = ul.find("li:first");
		var left = parseInt(ul.css('left'));
		left = isNaN(left) ? 0 : left;
	
		ul.animate({
			'left': left-img.width()
		}, {
			complete: function(){
				isAnim = false;
			}
		});
		$(liHidden[0]).fadeIn(200);
		
		++curIndex;
		
		if( liHidden.length == 1 ) $(this).hide(250);
		if( $(this).prev().css('display') == 'none' ) $(this).prev().show(250);
		
		return false
	});
	
	$('#body div.gallery a.prev_slide').click(function(){
		if( isAnim ) return false;
		
		isAnim = true;
		var div = $(this).parent().find('div');
		var ul = div.find('ul');	
		var img = ul.find("li:first");
		var left = parseInt(ul.css('left'));
		left = isNaN(left) ? 0 : left;
	
		ul.find('li:visible:eq('+(curIndex+3)+')').fadeOut(200);
		ul.animate({
			'left': left+img.width()
		}, {
			complete: function(){
				isAnim = false;
			}
		});
		
		--curIndex;
		
		if( curIndex == 0 ) $(this).hide(250);
		if( $(this).next().css('display') == 'none' ) $(this).next().show(250);
		
		return false
	});
	
	$('#body div.gallery ul a').click(function(){
		var expl = $('#main').attr('src').split('/');
		expl[expl.length-1] = $(this).find('img').attr('title');
		$('#main').attr('src', expl.join('/'));
		
		return false
	})
})
