(function($) {
	$.fn.turnPage = function() {
		return this.each(function() {

			$descWrapper = $('#plan_description > ul', this);
			$descItems = $descWrapper.find('> li');
			$descFirst = $descItems.filter(':first');
			$descLast = $descItems.filter(':last');
			$descCurrent = $descFirst;

			$stickerWrapper = $('#plan_sticker > ul', this);
			$stickerItems = $stickerWrapper.find('> li');
			$stickerFirst = $stickerItems.filter(':first');
			$stickerLast = $stickerItems.filter(':last');
			$stickerCurrent = $stickerFirst;

			$imageWrapper = $('#plan_image', this);

			pages = $descItems.size();
			currentPage = 1;

			function turn(direction) {

				switch(direction) {
					case 'next':
						if(currentPage < pages) {
							$followingDesc = $descCurrent.next();
							$followingSticker = $stickerCurrent.next();
							currentPage++;
						}
						else {
							$followingDesc = $descFirst;
							$followingSticker = $stickerFirst;
							currentPage = 1;
						}
					break;

					case 'previous':
						if(currentPage == 1) {
							$followingDesc = $descLast;
							$followingSticker = $stickerLast;
							currentPage = pages;
						}
						else {
							$followingDesc = $descCurrent.prev();
							$followingSticker = $stickerCurrent.prev();
							currentPage--;
						}
					break;
				}

				$descCurrent.find('div').fadeOut('slow', function() {
					$followingDesc.css('display', 'inline').find('div').hide().fadeIn('slow');
					$descCurrent = $followingDesc;
				});

				$stickerCurrent.fadeOut('slow', function() {
					$followingSticker.fadeIn('slow');
					$stickerCurrent = $followingSticker;
				});

				$imageWrapper.animate({scrollLeft: (currentPage-1)*567}, 'normal');

			}

			$('#previous').click(function() {
				if($('div').is(':animated') || $('li').is(':animated')) {
					return;
				}
				else {
					return turn('previous');
				}
			});
			
			$('#next').click(function() {
				if($('div').is(':animated') || $('li').is(':animated')) {
					return;
				}
				else {
					return turn('next');
				}
			});
		});
	};
})(jQuery);

$(document).ready(function() {
	$('#plans').turnPage();
});
