<%@ Control Language="C#" ClassName="GalleryTable" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ OutputCache Shared="true" Duration="60" VaryByParam="none" %>

<script runat="server">
	//This variable specifies relative path to the folder, where the gallery with uploaded files is located.
	//Do not forget about the slash in the end of the folder name.
	readonly string _galleryPath = "../UploadedFiles/";
	readonly int _pageSize = 5;
	int _pageIndex = 0;
	XmlNodeList nodes = null;

	private void Page_Load(System.Object sender, System.EventArgs e)
	{
		string fileName = Server.MapPath(_galleryPath + "Descriptions.xml");
		//Invalidate cache when Description.xml is changed		
		this.CachePolicy.Dependency = new CacheDependency(fileName);
		//Invalidate cache when request other page
		this.CachePolicy.VaryByParams["page"] = true;

		if (Request["page"] == null || !int.TryParse(Request["page"], out _pageIndex) || _pageIndex < 0)
		{
			_pageIndex = 0;
		}

		if (File.Exists(fileName))
		{
			XmlDocument descriptions = new XmlDocument();
			descriptions.Load(fileName);

			if (descriptions.DocumentElement.ChildNodes.Count > 0)
			{
				nodes = descriptions.SelectNodes("//file");
			}
		}
	}

	private string EncodeFileName(string value)
	{
		return Uri.EscapeDataString(value);
	}
</script>

<% 
	if (nodes != null)
	{ 
%>
<%--Render image list--%>
<ul class="list">
	<% 
	for (int i = _pageIndex * _pageSize; i < _pageIndex * _pageSize + _pageSize && i < nodes.Count; i++)
	{
		XmlElement node = (XmlElement)nodes[i];
	%>
	<li><a rel="lightbox" class="content" href="<%= _galleryPath + EncodeFileName(node.GetAttribute("name")) + "?t=" + DateTime.Now.Ticks.ToString() %>"
		target="_blank" title="<%= Server.HtmlEncode(node.GetAttribute("description"))%>">
		<div class="image">
			<img src="<%= _galleryPath + "Thumbnails/" + EncodeFileName(node.GetAttribute("thumbName")) + "?d=ajaxdemo"%>"
				alt="<%= Server.HtmlEncode(node.GetAttribute("name"))%>" /></div>
		<h3>
			<%= Server.HtmlEncode(node.GetAttribute("name"))%></h3>
		<p>
			Dimension:&nbsp;<%= Server.HtmlEncode(node.GetAttribute("width"))%>x<%= Server.HtmlEncode(node.GetAttribute("height"))%>
		</p>
		<p>
			Description:&nbsp;<%= Server.HtmlEncode(node.GetAttribute("description"))%>
		</p>
	</a></li>
	<% 
	}
	%>
</ul>
<%--Render pager--%>
<div class="pager">
	<%
	if (System.Math.Ceiling((double)nodes.Count / (double)_pageSize) > 1)
	{
		for (int i = 0; i < System.Math.Ceiling((double)nodes.Count / (double)_pageSize); i++)
		{
	%>
	<% 
	if (i == _pageIndex)
	{ 
	%>
	<span>
		<%= i + 1%></span>
	<%
	}
	else
	{%>
	<a href="#<%= i %>">
		<%= i + 1%></a>
	<%
	}
		}
	}
	%>
</div>
<% }
	else
	{%>
	<p style="line-height: 400px; text-align: center;">No uploaded images</p>
<% } %>