var scroller;
var startIndex = -1;

function resetAlbumScroller() {
	$('.widget.album_photos .panel li').each(
		function(i) {
			if($(this).find('a.current').size() == 1) {
				startIndex = i;
			}
		}
	);
	
	scroller = $('.widget.album_photos .panel').scrollable(
		{
			api: true,
			size: 3,
			step: 3,
			clickable: false
		}
	);
	
	if(startIndex > 0) {
		scroller.seekTo(startIndex, 0);
	}
}

function expandAlbum() {
	$('.widget.album_photos .panel').each(
		function() {
			$('.widget.album_photos .prev_next a').fadeOut();
			$(this).addClass('panel-noscroll');
			$(this).removeClass('panel');
			height = $(this).find('ul').height();
			
			$(this).css(
				{
					"height": '124px'
				}
			);

			$(this).animate(
				{
					"height": "" + height + "px"
				}
			);
			
			$('.widget.album_photos .widget_footer a').html('Show 3 at a time');
			$('.widget.album_photos .widget_footer a').removeClass('stop-scrolling');
			$('.widget.album_photos .widget_footer a').addClass('restart-scrolling');
			if ($('.widget.album_photos .widget_footer a.restart-scrolling').length > 0) {
				$('.widget.album_photos .widget_footer a.restart-scrolling').unbind('click');
				$('.widget.album_photos .widget_footer a.restart-scrolling').bind('click',
					stopScrolling
				);
			}
		}
	);
}

function contractAlbum() {
	$('.widget.album_photos .panel-noscroll').each(
		function() {
			$('.widget.album_photos .prev_next a').fadeIn();
			
			$(this).animate(
				{
					height: '114px'
				},
				function() {
					$(this).removeClass('panel-noscroll');
					$(this).addClass('panel');
					
					if(startIndex > 0) {
						scroller.seekTo(startIndex);
					}
					
					$('.widget.album_photos .widget_footer a').html('View all');
					$('.widget.album_photos .widget_footer a').removeClass('start-scrolling');
					$('.widget.album_photos .widget_footer a').addClass('stop-scrolling');
					$('.widget.album_photos .widget_footer a.stop-scrolling').bind('click',
						startScrolling
					);
				}
			);
		}
	);
}

function startScrolling() {
	index = scroller.getPageIndex();
	if(index > 0) {
		scroller.begin(500, expandAlbum);
	} else {
		expandAlbum();
	}
	
	return false;
}

function stopScrolling() {
	contractAlbum();
	return false;
}

$(document).ready(
	function() {
		resetAlbumScroller();
		
		$('.widget.album_photos .widget_footer a').addClass('stop-scrolling');
		$('.widget.album_photos .widget_footer a.stop-scrolling').bind('click',
			startScrolling
		);
	}
);