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

	SELECT @count = COUNT(*) FROM tblVideos;

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

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

	SELECT @newid AS ID;
END

