ALTER PROCEDURE [dbo].[NBGetChannels] 
	@principal int,
	@isWizdomOrNoticeboardAdmin bit,
	@FilterArchived bit,
	@FilterCurrent bit,
	@FilterFuture bit,
	@FilterMine bit,
	@FilterUnread bit,
	@FilterChannel int = null,
	@SearchTerm nvarchar(max) = null
AS
BEGIN

SELECT  
	AllowedChannels.ChannelID,
	AllowedChannels.RightsLevel,
	AllowedChannels.RightsChannel,
	AllowedChannels.ParentChannelID,
	AllowedChannels.Name,
	AllowedChannels.SortOrder,
	AllowedChannels.CanContainItems,
	AllowedChannels.CanOnlyEditItsOwn,
	(
		SELECT COUNT(NB_Channel_Item.NB_Item_ItemID) 
		from NB_Channel_Item 
			inner join NB_Item on NB_Item.ItemID = NB_Channel_Item.NB_Item_ItemID
			LEFT OUTER JOIN NB_Read on NB_Read.ItemID = NB_Item.ItemID and NB_Read.PrincipalID = @principal
		where NB_Channel_Item.NB_Channel_ChannelID = AllowedChannels.ChannelID
			and
			(
				Startdate < GETUTCDATE() or 
				AuthorID = @principal or 
				AlternateAuthorID = @principal or 
				@isWizdomOrNoticeboardAdmin = 1
			)
			and 
			(
				(@FilterArchived = 0 and @FilterCurrent = 0 and @FilterFuture = 0)  or
				(@FilterArchived = 1 and Enddate < GETUTCDATE()) or
				(@FilterCurrent = 1 and Startdate < GETUTCDATE() AND GETUTCDATE()<Enddate) or
				(@FilterFuture = 1 and GETUTCDATE() < Startdate)
			)
			and
			(
				@FilterMine = 0 or @FilterMine = 1 and (AuthorID = @principal or AlternateAuthorID = @principal)
			)
			and 
			(
				@SearchTerm is null or 
				NB_Item.Heading Like '%' + @SearchTerm + '%'  or 
				NB_Item.Summary Like '%' + @SearchTerm + '%' or 
				NB_Item.Content Like '%' + @SearchTerm + '%' or 
				NB_Item.TranslatedValues Like '%' + @SearchTerm + '%'
			)
			and
			(
				@FilterUnread = 0 or NB_Read.ItemID is null
			)
		) as itemCount,
		Rights.Rights,
		AllowedChannels.BreakRightsInherit
	FROM NB_GetMyChannels(@principal,@isWizdomOrNoticeboardAdmin,null,null) as AllowedChannels -- note function call!
	CROSS APPLY (
		select (	
			select 
				NB_ChannelRights.Level, 
				principal.principalID, 
				principal.displayName, 
				principal.loginName,
				principal.GroupId,
				Principal.Type
			from NB_ChannelRights
			inner join Principal on Principal.PrincipalID = NB_ChannelRights.PrincipalID
			where AllowedChannels.ChannelID = NB_ChannelRights.ChannelID AND AllowedChannels.BreakRightsInherit = 1 AND @isWizdomOrNoticeboardAdmin = 1
			for XML PATH, root ('rows')
		) Rights
	) Rights
	WHERE (@FilterChannel is null or AllowedChannels.ChannelID = @FilterChannel)
GROUP by 
	AllowedChannels.ChannelID, 
	AllowedChannels.RightsLevel, 
	AllowedChannels.RightsChannel, 
	AllowedChannels.ParentChannelID,
	AllowedChannels.Name,
	AllowedChannels.SortOrder,
	AllowedChannels.CanContainItems,
	AllowedChannels.CanOnlyEditItsOwn,
	AllowedChannels.BreakRightsInherit,
	Rights.Rights
ORDER BY ChannelID

END