CREATE PROCEDURE [dbo].[spFlipPicture]
	@id bigint,
	@step char(1),
	@category varchar(100)
AS
BEGIN
	DECLARE @count bigint;
	DECLARE @newid bigint;

	SELECT @count = COUNT(*) FROM tblPictures;

	IF (@step = 'F')
		BEGIN
			IF (@category = 'ALL')
				BEGIN
					SET @newid = (SELECT TOP 1(picture_id) FROM tblPictures WHERE picture_id > @id);
				END
			ELSE
				BEGIN
					SET @newid = (SELECT TOP 1(picture_id) FROM tblPictures WHERE picture_id > @id AND category_name = @category);
				END
		END
	ELSE IF (@step = 'B')
		BEGIN
			IF (@category = 'ALL')
				BEGIN
					SET @newid =  (SELECT TOP 1(picture_id) FROM tblPictures WHERE picture_id < @id  ORDER BY picture_id DESC);
				END
			ELSE
				BEGIN
					SET @newid =  (SELECT TOP 1(picture_id) FROM tblPictures WHERE picture_id < @id  AND category_name = @category ORDER BY picture_id DESC);
				END
		END

	IF (@newid IS NULL)
		BEGIN
			IF (@step = 'F')
				BEGIN
					IF (@category = 'ALL')
						BEGIN
							SET @newid = (SELECT MIN(picture_id) FROM tblPictures);
						END
					ELSE
						BEGIN
							SET @newid = (SELECT MIN(picture_id) FROM tblPictures WHERE category_name = @category);
						END
				END
			ELSE
				BEGIN
					IF (@category = 'ALL')
						BEGIN
							SET @newid = (SELECT MAX(picture_id) FROM tblPictures);
						END
					ELSE
						BEGIN
							SET @newid = (SELECT MAX(picture_id) FROM tblPictures WHERE category_name = @category);
						END
				END
		END

	SELECT @newid AS ID;
END
