protected void BXForumGrid_Select(object sender, BXSelectEventArgs e)
	{
		BXFilter filter = new BXFilter(new BXFilterItem(BXForum.Fields.CheckPermissions, BXSqlFilterOperators.Equal, new string[] { BXForum.Operations.ForumAdminManage }));
		filter.Add(new BXFilter(BXForumFilter.CurrentFilter, BXForum.Fields));

		BXOrderBy orderBy;

		if (String.IsNullOrEmpty(e.SortExpression))
			orderBy = new BXOrderBy(
				new BXOrderByPair(BXForum.Fields.Category.Sort, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Category.Id, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Sort, BXOrderByDirection.Asc),
				new BXOrderByPair(BXForum.Fields.Name, BXOrderByDirection.Asc)
			);
		else
			orderBy = new BXOrderBy(BXForum.Fields, e.SortExpression);

		e.Data = BXForum.GetList(
			filter,
			orderBy,
			null, 
			new BXQueryParams(e.PagingOptions),
			BXTextEncoder.EmptyTextEncoder
		);
	}
    protected void BXSubscriptionsGrid_Select(object sender, BXSelectEventArgs e)
    {
        if (UserId <= 0)
        {
            e.Data = new List<BXSubscriptionsSelect>();
            return;
        }
        currentFilter = new BXFilter(new BXFilterItem(BXForumSubscription.Fields.Subscriber.Id,BXSqlFilterOperators.Equal,UserId));
        currentFilter.Add(new BXFilter(BXSubscriptionsFilter.CurrentFilter, BXForumSubscription.Fields));
        //BXSubscriptionsFilter.CurrentFilter.con
        BXOrderBy orderBy;

        if (String.IsNullOrEmpty(e.SortExpression))
            orderBy = new BXOrderBy(new BXOrderByPair(BXForumSubscription.Fields.Id, BXOrderByDirection.Asc));
        else
            orderBy = new BXOrderBy(BXForumSubscription.Fields, e.SortExpression);

        BXForumSubscriptionCollection subs = BXForumSubscription.GetList(
                                                            currentFilter,
                                                            orderBy,
                                                            new BXSelectAdd(BXForumSubscription.Fields.Topic,BXForumSubscription.Fields.Forum),
                                                            new BXQueryParams(e.PagingOptions),
                                                            BXTextEncoder.EmptyTextEncoder
                                                        );
        List<BXSubscriptionsSelect> list = subs.ConvertAll<BXSubscriptionsSelect>(delegate(BXForumSubscription input)
            {
                string siteName = String.Empty;
                if (sites.ContainsKey(input.SiteId)) siteName = sites[input.SiteId];
                else throw new KeyNotFoundException("site is not found");
            return new BXSubscriptionsSelect(   
                                                input.Id, input.Forum!=null ? input.Forum.Name:"", 
                                                input.Topic!=null? input.Topic.Name:"", input.OnlyTopic, 
                                                input.DateStart, siteName,
                                                GetMessageRaw(input.TopicId>0? "ColumnText.Topic" : input.OnlyTopic ? "ColumnText.OnlyTopic" : "ColumnText.FullForum")
                                            );

            }
        );

        e.Data = list;

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        #region InitializeStartup
        SectionId = Parameters.Get("SectionId", 0);

        bool COUNT_ELEMENTS = Parameters.Get<bool>("COUNT_ELEMENTS", false);
        string SortByWhat = Parameters.Get<string>("SortBy", "sort");
        string OrderByWhat = Parameters.Get<string>("OrderBy", "asc");
        #endregion

        BXParamsBag<object> request = new BXParamsBag<object>();

        if (EnableSef)
        {
            BXParamsBag<string> urlToPage = new BXParamsBag<string>();
            urlToPage.Add("Catalog.List0", SectionURL);
            urlToPage.Add("Catalog.List1", SectionPageURL);

            MapVariable(SEFFolder, urlToPage, request);

            Results["ParamSectionId"] = ParamSectionId;
            Results["ParamSectionCode"] = ParamSectionCode;
        }
        else
        {
            BXParamsBag<string> variableAlias = new BXParamsBag<string>();
            variableAlias[ParamSectionId] = AliasSectionId;
            variableAlias[ParamSectionCode] = AliasSectionCode;

            MapVariable(variableAlias, request);

            Results["ParamSectionId"] = AliasSectionId;
            Results["ParamSectionCode"] = AliasSectionCode;
        }

        //IBlockId = request.Get("iblock_id", IBlockId);
        SectionId = request.Get(ParamSectionId, SectionId);
        SectionCode = request.Get<string>(ParamSectionCode, SectionCode);

        // Rewrite default variables
        request.Add(ParamSectionId, SectionId);
        request.Add(ParamSectionCode, SectionCode);        

        Results["SectionURL"] = SectionURL;

        Results["SectionId"] = SectionId;
        Results["SectionCode"] = SectionCode;

        if (EnableSef)
            Results["CatalogRoot"] = BXPath.ToVirtualAbsolutePath(SEFFolder);
        else
            Results["CatalogRoot"] = Parameters.Get<string>("CatalogRoot", BXSefUrlManager.CurrentUrl.AbsolutePath);

        if (!IsCached(IBlockId, SectionId, SectionCode))
        {
            if (IBlockId > 0)
            {
                List<Dictionary<string, string>> sList = new List<Dictionary<string, string>>();
                                        
                int i = 0, baseDepth = 0;
                BXIBlockSectionCollection sections = null;


                if (SectionId <= 0 && String.IsNullOrEmpty(SectionCode))
                {
                    sections = BXIBlockSection.GetTree(IBlockId, Depth + 1);
                }
                else
                {
                    #region SectionList
                    BXOrderBy sOrder = new BXOrderBy();
					sOrder.Add(BXIBlockSection.Fields, String.Format("{0} {1}", SortByWhat, OrderByWhat));
					//sOrder.Add(BXIBlockSection.Fields, String.Format("{0} {1}", "id", "asc"));
                    BXIBlockSection parentSection = null;

                    if (String.IsNullOrEmpty(SectionCode))
                    {
                        if (SectionId > 0)
                            parentSection = BXIBlockSection.GetById(SectionId);
                    }
                    else
                    {
                        BXFilter sParentFilter = new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.Code, BXSqlFilterOperators.Equal, SectionCode),
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
                            );

                        BXIBlockSectionCollection sCol = BXIBlockSection.GetList(sParentFilter, null);
                        if (sCol != null && sCol.Count > 0)
                            parentSection = sCol[0];
                    }

                    BXFilter sFilter = new BXFilter(
							new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId),
							new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
                        );

                    if (parentSection != null)
                    {
                        ParentSectionId = parentSection.Id;                        
                        baseDepth = parentSection.DepthLevel;

						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.LeftMargin, BXSqlFilterOperators.GreaterOrEqual, parentSection.LeftMargin));
						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.RightMargin, BXSqlFilterOperators.Less, parentSection.RightMargin));
						sFilter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.LessOrEqual, parentSection.DepthLevel + Depth));

                        sections = BXIBlockSection.GetList(sFilter, sOrder);
                    }
                    #endregion
                    #region NavChain
                    BXIBlockSectionCollection navChain = null;

                    if (SectionId > 0)
                    {
                        navChain = BXIBlockSection.GetNavChain(SectionId);
                    }
                    else if (ParentSectionId > 0)
                    {
                        navChain = BXIBlockSection.GetNavChain(ParentSectionId);                        
                    }

                    Results["NavChain"] = navChain;
                    SetupNavchain(navChain, request);  
                    #endregion
                }
                Results["DataVolume"] = (sections != null) ? sections.Count : 0;
				if (sections != null)
				{
					string str = String.Empty;
					if (EnableSef)
						str = String.Concat(SEFFolder, "/", SectionURL);
					else
						str = SectionURL;

					foreach (BXIBlockSection s in sections)
					{
						Dictionary<string, string> v = new Dictionary<string, string>();
						if (s.DepthLevel == 1)
						{
							i++;
							v.Add("I", (i < 10) ? "0" + i : i.ToString());
						}
						v.Add("SectionId", s.Id.ToString());
						v.Add("Depth", (s.DepthLevel - baseDepth).ToString());
						v.Add("Name", s.Name);
						if (COUNT_ELEMENTS)
							v.Add("ElementsCount", s.ElementsCount.ToString());
						if (!String.IsNullOrEmpty(SectionURL))
						{
							request["iblock_id"] = s.IBlockId;
							request["section_id"] = s.Id;
							request["section_code"] = String.IsNullOrEmpty(s.Code) ? String.Empty : s.Code;
							v.Add("Path", BXUri.ToRelativeUri(MakeLink(str, request)));
						}
						sList.Add(v);
					}
				}

                Results["Section"] = sList;

                Results["EnableAjaxA"] = Parameters.Get<bool>("EnableAjax", false)?
                    "EnableAjax=\"True\"": "";
            }

            IncludeComponentTemplate();
        }
        else
        {
             // 1. NavChain
            if (Results.ContainsKey("NavChain")) SetupNavchain((BXIBlockSectionCollection)Results["NavChain"], request);
        }
	}
	protected void BXUsersGrid_Select(object sender, BXSelectEventArgs e)
	{
        BXFilter filter = new BXFilter();
        filter.Add(new BXFilter(BXUsersFilter.CurrentFilter, BXForumUser.Fields));

        BXOrderBy orderBy;

        if (String.IsNullOrEmpty(e.SortExpression))
            orderBy = new BXOrderBy(new BXOrderByPair(BXForumUser.Fields.Id, BXOrderByDirection.Asc));
        else
            orderBy = new BXOrderBy(BXForumUser.Fields, e.SortExpression);

        BXForumUserCollection subs = BXForumUser.GetList(   filter, 
                                                            orderBy,
                                                            new BXSelectAdd(BXForumUser.Fields.User,BXForumUser.Fields.SubscriptionsCount),
                                                            new BXQueryParams(e.PagingOptions),
                                                            BXTextEncoder.EmptyTextEncoder
                                                        );
        List<SubscriptionsGridSelect> list = new List<SubscriptionsGridSelect>();
        string msg = GetMessage("GridText.ToolTip.EditUser");
        foreach (BXForumUser u in subs)
            list.Add(new SubscriptionsGridSelect(u.User,u,msg));
        e.Data = list;
 
	}
    protected void Page_Load(object sender, EventArgs e)
    {
        #region SetupParameters
        SectionId = Parameters.Get("SectionId", 0);

        ShowSubelements = Parameters.Get("ShowSubelements", true);

        SortBy1 = Parameters.Get("SortBy1", "sort");
        SortOrder1 = Parameters.Get("SortOrder1", "Desc");

        PerPageCount = Parameters.Get("PerPageCount", 30);
        PerLineCount = Parameters.Get("PerLineCount", 3);
        Properties = Parameters.GetListString("Properties");

        string PropertyKeywords = Parameters.Get("PropertyKeywords", "-");
        string PropertyDescription = Parameters.Get("PropertyDescription", "-");
        bool AddAdminPanelButtons = Parameters.Get("AddAdminPanelButtons", false);
        bool ShowCompareButton = Parameters.Get("ShowCompareButton", false);
        bool SetPageTitle = Parameters.Get("SetPageTitle", true);
        bool CacheOnFilter = Parameters.Get("CacheOnFilter", false);

		Parameters["PagingAllowAll"] = false.ToString();
        /*bool PagerOverList = Parameters.GetBool("PagerOverList", false);
        bool PagerUnderList = Parameters.GetBool("PagerUnderList", false);
        string CategoryTitle = Parameters.GetString("CategoryTitle", "");
        bool PagerAlways = Parameters.GetBool("PagerAlways", true);
        string TemplateTitle = Parameters.GetString("TemplateTitle", "");
        bool UseInvertedNavigation = Parameters.GetBool("UseInvertedNavigation", false);
        int CacheTimeOnInvertedNavigation = Parameters.GetInt("CacheTimeOnInvertedNavigation", 36000);*/
        #endregion
        
        #region HackUnSef
        string PageKey = String.Empty;

        BXParamsBag<object> request = new BXParamsBag<object>();
        BXParamsBag<string> urlToPage = new BXParamsBag<string>();
        urlToPage.Add("SectionPage", SectionPageURL);
        urlToPage.Add("Section", SectionURL);
        
        if (EnableSef)
        {
            PageKey = MapVariable(SEFFolder, urlToPage, request, String.Empty);

            Results["ParamSectionId"] = ParamSectionId;
            Results["ParamElementId"] = ParamElementId;
            Results["ParamPageId"] = ParamPageId;
            Results["ParamElementCode"] = ParamElementCode;
            Results["ParamSectionCode"] = ParamSectionCode;
        }
        else
        {
            BXParamsBag<string> variableAliases = new BXParamsBag<string>();
			variableAliases.Add(ParamSectionId, AliasSectionId);
			variableAliases.Add(ParamElementId, AliasElementId);
			variableAliases.Add(ParamPageId, AliasPageId);
			variableAliases.Add(ParamSectionCode, AliasSectionCode);
			variableAliases.Add(ParamElementCode, AliasElementCode);
            MapVariable(variableAliases, request);

            Results["ParamSectionId"] = AliasSectionId;
            Results["ParamElementId"] = AliasElementId;
            Results["ParamPageId"] = AliasPageId;
            Results["ParamElementCode"] = AliasElementCode;
            Results["ParamSectionCode"] = AliasSectionCode;
        }

        SectionId = request.Get(ParamSectionId, SectionId);
        //ElementId = request.Get(ParamElementId, ElementId);
        PageId = request.Get(ParamPageId, PageId);
        ElementCode = request.Get<string>(ParamElementCode, ElementCode);
        SectionCode = request.Get<string>(ParamSectionCode, SectionCode);

        // Rewrite default variables
        request.Add(ParamSectionId, SectionId);
        //request.Add(ParamElementId, ElementId);
        request.Add(ParamElementCode, ElementCode);
        request.Add(ParamSectionCode, SectionCode);

        if (!EnableSef)
        {
            if (PageId > 0) PageKey = "SectionPage";
            //else if (ElementId > 0 || !String.IsNullOrEmpty(ElementCode)) PageKey = "Element";
            else if (SectionId > 0 || !String.IsNullOrEmpty(SectionCode)) PageKey = "Section";
        }

        Results["SectionURL"] = SectionURL;
        Results["SectionPageURL"] = SectionPageURL;
        Results["ElementURL"] = ElementURL;

        Results["SectionId"] = SectionId;
        //Results["ElementId"] = ElementId;
        Results["PageId"] = PageId;
        Results["ElementCode"] = ElementCode;
        Results["SectionCode"] = SectionCode;

        Results["PageKey"] = PageKey;
        #endregion

        if (!IsCached(IBlockTypeId, IBlockId, SectionId, PageId, SectionCode))
        {
			if (IBlockId > 0)
			{
				#region MakeComponentDataFilter
				BXIBlockElementCollection es = null;

				BXFilter esf = new BXFilter();
				BXOrderBy eso = new BXOrderBy();

				esf.Add(new BXFilterItem(BXIBlockElement.Fields.Active, BXSqlFilterOperators.Equal, "Y"));

				eso.Add(BXIBlockElement.Fields, String.Format("{0} {1}", SortBy1, SortOrder1));

				if (IBlockId > 0)
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, IBlockId));
				}
				if (!String.IsNullOrEmpty(SectionCode))
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.Code, BXSqlFilterOperators.Equal, SectionCode));
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
				}
				else if (SectionId > 0)
				{
					esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, SectionId));
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
				}
				else
				{
					if (ShowSubelements)
					{
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.IncludeParentSections, BXSqlFilterOperators.Equal, "Y"));
					}
					else
						esf.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, "0"));
				}
				#endregion

				#region Paging Operations
				string PageUrlTemplate = String.Empty;
				string DefaultPageUrl = String.Empty;
				if (EnableSef)
				{
					DefaultPageUrl = BXComponentManager.MakeLink(SEFFolder, SectionURL);
					PageUrlTemplate = BXComponentManager.MakeLink(SEFFolder, SectionPageURL);
				}
				else
				{
					DefaultPageUrl = SectionURL;
					PageUrlTemplate = SectionPageURL;
				}

				BXQueryParams queryParams = PreparePaging(
					delegate
					{
						return BXIBlockElement.Count(esf);
					},
					request,
					Results.Get<string>("ParamPageId"),
					false,
					DefaultPageUrl,
					PageUrlTemplate,
					string.Empty
				);
				es = BXIBlockElement.GetList(esf, eso, null, queryParams);

				#endregion

				#region SetPageTitle
				if (SetPageTitle)
				{
					string PageTitle = Parameters.Get<string>("SectionTitle", String.Empty);
					if (String.IsNullOrEmpty(PageTitle))
					{
						BXIBlockSection rootSection = null;
						if (!String.IsNullOrEmpty(SectionCode))
						{
							BXFilter sParentFilter = new BXFilter(
									new BXFilterItem(BXIBlockSection.Fields.Code, BXSqlFilterOperators.Equal, SectionCode),
									new BXFilterItem(BXIBlockSection.Fields.Active, BXSqlFilterOperators.Equal, "Y")
									);

							BXIBlockSectionCollection sCol = BXIBlockSection.GetList(sParentFilter, null);
							if (sCol != null && sCol.Count > 0)
								rootSection = sCol[0];
						}
						else if (SectionId > 0)
							rootSection = BXIBlockSection.GetById(SectionId);

						if (rootSection != null)
							PageTitle = rootSection.Name;
						else
						{
							BXIBlock iblock = BXIBlock.GetById(IBlockId);
							if (iblock != null)
								PageTitle = iblock.Name;
						}
					}

					Results["SectionName"] = PageTitle;
				}
				#endregion

				if (es != null)
				{
					Results["DataVolume"] = es.Count;
				}

				if (es != null && es.Count > 0)
				{
					List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
					foreach (BXIBlockElement el in es)
					{
						Dictionary<string, string> v = new Dictionary<string, string>();

						string imageUrl = String.Empty;
						BXFile image = el.DetailImageId > 0 ? el.DetailImage : el.PreviewImage;

						if (image != null)
							imageUrl = String.Format(
							"{0}ImageResizer.ashx?path={1}&width={2}&height={3}&fit={4}",
							BXUri.ToAbsoluteUri("~/bitrix/handlers/Main/"),
							UrlEncode(image.FileVirtualPath),
							Parameters.Get("PreviewWidth", 150),
							Parameters.Get("PreviewHeight", 150),
							!Parameters.Get<bool>("FlickrMode", false));

						v.Add("Id", el.Id.ToString());
						v.Add("Title", el.Name);
						v.Add("PreviewText", el.PreviewText);
						v.Add("PreviewTextType", el.PreviewTextType.ToString());
						v.Add("PreviewImage", imageUrl);

						request.Add(ParamElementId, el.Id);
						request.Add(ParamElementCode, String.IsNullOrEmpty(el.Code) ? String.Empty : el.Code);
						if (EnableSef)
							v.Add("ElementLink", BXStringUtility.HtmlEncodeEx(MakeLink(SEFFolder, ElementURL, request)));
						else
							v.Add("ElementLink", BXStringUtility.HtmlEncodeEx(MakeLink(ElementURL, request)));

						data.Add(v);

						Dictionary<string, BXCustomProperty> v2 = new Dictionary<string, BXCustomProperty>();
						BXCustomPropertyCollection props = el.Properties;
						if (props != null)
							foreach (KeyValuePair<string, BXCustomProperty> kcs in props)
								if (Properties.Exists(delegate(string x)
								{
									return x.Equals(kcs.Key, StringComparison.InvariantCultureIgnoreCase);
								}))
									v2[kcs.Key] = kcs.Value;

						Results["DataProperties_" + el.Id] = v2;
					}

					Results["Data"] = data;
				}

				Results["EnableAjaxA"] = Parameters.Get<bool>("EnableAjax", false) ? "EnableAjax=\"True\"" : "";
			}
			IncludeComponentTemplate();
        }

		if (SetPageTitle && Results.ContainsKey("SectionName") && Results["SectionName"] != null)
		{
			string PageTitle = Results.Get<string>("SectionName");

			if (Page is BXPublicPage)
				(Page as BXPublicPage).BXTitle = PageTitle;
		}
	}
	//METHODS
	protected void Page_Load(object sender, EventArgs e)
	{
		if (IBlockId > 0)
		{
			//if (EnableSef)
			//{
			//	MapVariable(Parameters.Get<string>("SEFFolder", "/photogallery"), Parameters.Get<string>("SEF_Album"), Results);
			//}
			//else
			//{
			//    BXParamsBag<string> variableAlias = new BXParamsBag<string>();
			//    variableAlias["AlbumID"] = Parameters.Get<string>("ParamAlbum", "Album");
			//    variableAlias["PageID"] = Parameters.Get<string>("ParamAlbumPage", "Album");
			//    variableAlias["PageShowAll"] = Parameters.Get<string>("ParamAlbumShowAll", "Album");
			//    MapVariable(variableAlias, Results);

			//    if (AlbumId > 0)
			//    {
			//        Results["AlbumParentID"] = BXInfoBlockSectionManagerOld.GetById(AlbumId).ParentSectionId;
			//    }
			//}

			int albumParent = 0;


			if (BXIBlock.IsUserCanOperate(IBlockId, BXIBlock.Operations.IBlockModifySections))
				CanModify = true;

			if (AlbumId > 0)
			{
				//load album
				AlbumItem = BXIBlockSection.GetById(AlbumId, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);

				if (AlbumItem != null)
				{
					albumParent = AlbumItem.SectionId;



					if (Page is BXPublicPage)
						((BXPublicPage)Page).MasterTitle = Server.HtmlDecode(AlbumItem.Name);
					Page.Title = AlbumItem.Name;
					IsNested = true;

					BXFile image = AlbumItem.Image;

					if (image != null)
					{
						Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
							   BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 75),
							   Parameters.Get("PreviewHeight", 75));

						AlbumCoverUrl = imageInfo.GetUri();
					}

					FillNavChain();
				}
			}

			BackUrl = GetAlbumUrl(albumParent);

			UploadUrl = MakeLink(Parameters.Get<string>("UrlTemplateUpload", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), AlbumId);
			AddUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumAdd", BXConfigurationUtility.Constants.ErrorHref), AlbumId);

			BXFilter filter = new BXFilter();
			BXPagingParams pagingParams = new BXPagingParams();
			if (AlbumItem != null)
			{

				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.SectionId, BXSqlFilterOperators.Equal, AlbumItem.Id));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.Less, Album.DepthLevel + 2));

				BXFilter photoFilter = new BXFilter();
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				photoFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, Album.SectionId));

				BXParamsBag<object> mapParams = new BXParamsBag<object>();
		
				mapParams["AlbumID"] = AlbumId;
				
				
				pagingParams.AllowPaging = true;
				string pageId = Request.QueryString["page"];
				int photoId = Parameters.Get<int>("PhotoId",0);// если шаблон фото детально передал параметр, 
				//значит нужно показать элемент вместе с текущей страницей для вывода в слайдер
				pagingParams = PreparePagingParams();
				if (photoId > 0 && pageId==null)
				{
					//Determine page
					
					BXIBlockElement currentPhoto = BXIBlockElement.GetById(photoId);

					int count = BXIBlockElement.Count(new BXFilter(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, AlbumItem.Id),
																	new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, currentPhoto.IBlockId)));


					if (currentPhoto != null)
					{
						BXFilter countFilter = new BXFilter();
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.ID, BXSqlFilterOperators.Less, currentPhoto.Id));
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, currentPhoto.IBlockId));
						countFilter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, AlbumItem.Id));

						int index = BXIBlockElement.Count(countFilter);

						BXPagingHelper helper = ResolvePagingHelper(count, pagingParams);
						pagingParams.Page = helper.GetOuterIndex(helper.GetPageIndexForItem(index));
						Component.Parameters["PagingPageId"] = (pagingParams.Page ?? 1).ToString();
						Component.Parameters["PageId"] = (pagingParams.Page ?? 1).ToString();
					}
				}




				BXQueryParams queryParams = PreparePaging(
					pagingParams,
										delegate
										{
											return BXIBlockElement.Count(photoFilter);
										},
					mapParams,
					"PageID",
					Parameters.Get<string>("UrlTemplateAlbum"),
					Parameters.Get<string>("UrlTemplateAlbumPage"),
					Parameters.Get<string>("UrlTemplateAlbumShowAll")
					);
				var photoOrderBy = new BXOrderBy();
				photoOrderBy.Add(BXIBlockElement.Fields, String.Format("{0} {1}", this.PhotoSortBy, this.PhotoSortOrder));
				PhotoItems = BXIBlockElement.GetList(photoFilter, photoOrderBy, null, queryParams, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
				PhotoDescriptionDictionary = new Dictionary<BXIBlockElement, PhotoDescription>();
				//Component.Parameters["PageId"] = (pagingParams.Page ?? 1).ToString();
				ComponentCache["PageId"] = (pagingParams.Page ?? 1).ToString();
				if (Photos.Count > 0)
				{
					foreach (BXIBlockElement photo in PhotoItems)
					{
						PhotoDescription photoDesc = new PhotoDescription();

						photoDesc.Preview = string.Empty;

						BXFile image = photo.DetailImageId > 0 ? photo.DetailImage : photo.PreviewImage;

						if (image == null)
							continue;

						Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
						BXImageUtility.GetResizedImage(image, Parameters.Get("PreviewWidth", 75),
						Parameters.Get("PreviewHeight", 75));
						photoDesc.Preview = imageInfo.GetUri();
						photoDesc.DetailUrl = image.GetUri();
						BXParamsBag<object> replace = new BXParamsBag<object>();
						replace.Add("PHOTOID", photo.Id);
						replace.Add("ALBUMID", AlbumId);
						if (!EnableSef)
						{
							photoDesc.PhotoUrl =
								string.Format("?{0}={1}", Parameters.Get<string>("ParamPhoto", "photo"), photo.Id);
						}
						else
						{
							photoDesc.PhotoUrl =
								MakeLink(Parameters.Get<string>("SEFFolder"), Parameters.Get<string>("SEF_Photo"), replace);
						}

						photoDesc.ActualCoverHeight = imageInfo.Height;
						photoDesc.ActualCoverWidth = imageInfo.Width;
						photoDesc.CurUserId = CurrentUserId;
						photoDesc.DetailHeight = image.Height;
						photoDesc.DetailWidth = image.Width;
						photoDesc.Element = photo;
						PhotoDescriptionDictionary[photo] = photoDesc;
						

					}
				}

				ParentAlbumId = Album.ParentSectionId;
			}
			else
			{
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockSection.Fields.DepthLevel, BXSqlFilterOperators.Less, 2));
				if (Page is BXPublicPage)
					((BXPublicPage)Page).MasterTitle = GetMessageRaw("Photogallery");
				Page.Title = GetMessageRaw("Photogallery");
				ParentAlbumId = 0;
			}
			var albumOrderBy = new BXOrderBy();
			albumOrderBy.Add(BXIBlockSection.Fields, String.Format("{0} {1}", this.AlbumSortBy, this.AlbumSortOrder));
			SectionItems = BXIBlockSection.GetList(filter, albumOrderBy, null, null, Bitrix.Services.Text.BXTextEncoder.EmptyTextEncoder);
			AlbumDescriptionDictionary = new Dictionary<BXIBlockSection, AlbumDescription>();

			if ((Sections.Count != 0) && (AlbumId > 0))
				IsParent = true;

			foreach (BXIBlockSection section in SectionItems)
			{
				AlbumDescription albumDesc = new AlbumDescription();

				filter = new BXFilter();
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.IBlock.ID, BXSqlFilterOperators.Equal, Parameters.Get("IBlockId", 0)));
				filter.Add(new BXFilterItem(BXIBlockElement.Fields.Sections.Section.ID, BXSqlFilterOperators.Equal, section.Id));

				BXIBlockElementCollection elements = BXIBlockElement.GetList(filter, null);

				albumDesc.CoverImageUrl =
					BXUri.ToRelativeUri(
						"~/bitrix/components/bitrix/photogallery.album/templates/.default/images/no_image.png");

				albumDesc.Count = elements.Count;

				albumDesc.Url = GetAlbumUrl(section.Id);
				albumDesc.EditUrl = MakeLink(Parameters.Get<string>("UrlTemplateAlbumEdit", BXConfigurationUtility.Constants.ErrorHref), section.Id);

				BXFile image = section.Image;

				if (image == null)
					foreach (BXIBlockElement element in elements)
					{
						image = element.PreviewImage;
						if (image != null)
							break;
					}

				albumDesc.IsCoverEmpty = true;
				if (image != null)
				{
				    Bitrix.Services.Image.BXImageInfo imageInfo = Bitrix.Services.Image.
					    BXImageUtility.GetResizedImage(
                        image, Parameters.Get("CoverWidth", 75),
					    Parameters.Get("CoverHeight", 75));

				    albumDesc.CoverImageUrl = imageInfo.GetUri();
				    albumDesc.IsCoverEmpty = false;
				}

				AlbumDescriptionDictionary[section] = albumDesc;

			}

		}

		IncludeComponentTemplate();
	}