/// <reference path="jquery-vsdoc.js" /> 
/// <reference path="jquery-select.js" /> 

jQuery(function()
{
	Trinet.Web.Site.Services.Newsfeeds.NewsfeedService.ListChannels(
		function(channelList)
		{
			jQuery("select[name=channelList]")
				.clearList(0)
				.addStaticItem("--Select One--")
				.loadList(channelList,
				{
					staticItemCount: 1,
					dataValueField: "ChannelName",
					dataTextField: "ChannelName"
				})
				.change(function()
				{
					if (-1 == this.selectedIndex || 0 == this.selectedIndex)
					{
						jQuery("select[name=categoryList]")
							.clearList(0)
							.addStaticItem("--Select a channel--");
					}
					else
					{
						var channel = channelList[this.selectedIndex - 1];
						jQuery("select[name=categoryList]")
							.clearList(0)
							.addStaticItem("--Select One--")
							.loadList(channel.ChildCategories,
							{
								staticItemCount: 1,
								dataValueField: "FeedName",
								dataTextField: "CategoryName"
							});
					}
				});
			
			jQuery("select[name=categoryList]")
				.clearList(0)
				.addStaticItem("--Select a channel--")
				.change(function()
				{
					if (-1 == this.selectedIndex || 0 == this.selectedIndex)
					{
						jQuery("#articleList").html("<em>Select a category</em>");
					}
					else
					{
						jQuery("#articleList").html("<em>Loading...</em>");
						
						var feedName = this.options[this.selectedIndex].value;
						Trinet.Web.Site.Services.Newsfeeds.NewsfeedService.LoadFeed(feedName,
							function(result)
							{
								var i = result.length - 1;
								if (null === result[i].HarvestTime)
								{
									result = result.slice(0, i);
								}
								
								var builder = new Trinet.UI.ListView();
								builder.set_layoutTemplate(Trinet.UI.ListView.loadTemplate($get("layoutTemplate")));
								builder.set_itemTemplate(Trinet.UI.ListView.loadTemplate($get("itemTemplate")));
								builder.set_itemSeparatorTemplate(Trinet.UI.ListView.loadTemplate($get("itemSeparator")));
								
								var list = $get("articleList");
								builder.bindElement(list, result, function(memberName, item)
								{
									var result = item[memberName];
									if ("HarvestTime" === memberName && null !== result)
									{
										result = result.format("dddd, dd MMMM yyyy hh:mm tt");
									}
									
									return result;
								});
							},
							function(error)
							{
								jQuery("#articleList").html("<em>Select a category</em>");
								alert("There was an error loading the feed.");
							}
						);
					}
				});
		},
		function(error)
		{
			jQuery("select[name=channelList]").clearList(0);
			alert("There was an error loading the list of categories.");
		}
	);
});
