$(function()
{
	var libraryText = 'View Technical Datasheet Library';
	var productText = 'Back to Featured Products';
	var productView = $('#gridBrandProducts');
	var fileView = null;
	var brand = $('h2').text().match(/^Brand - (.+)$/)[1].replace(/[^-\w\s]+/g, '').replace(/\s+/g, '-').replace(/-+/g, '-').toLowerCase();
	var switchButton = $('.products-files-switch a').text(libraryText);
	
	switchButton.click(function()
	{
		if (fileView === null)
		{
			$.post('../ajax.php?action=get-directory-listing',
			{
				brand: brand
			}, function(data)
			{
				fileView = generateList(data, 2).attr('id', 'file-view').hide().insertAfter(productView);
				fileView.find('li.file').each(function()
				{
					var $this = $(this);
					$this.wrapInner('<a href="' + $this.data('path') + '" />');
				});
				switchViews();
			}, 'json');
		}
		else
		{
			switchViews();
		}
		
		return false;
	});
	
	function switchViews()
	{
		if (productView.is(':visible'))
		{
			productView.slideUp('medium', function()
			{
				fileView.slideDown('medium');
			});
			
			switchButton.animate({ height: 'hide' }, 'medium', function()
			{
				switchButton.text(productText).animate({ height: 'show' }, 'medium');
			});
		}
		else
		{
			fileView.slideUp('medium', function()
			{
				productView.slideDown('medium');
			});
			
			switchButton.animate({ height: 'hide' }, 'medium', function()
			{
				switchButton.text(libraryText).animate({ height: 'show' }, 'medium');
			});
		}
	};
	
	function generateList(listing, depth)
	{
		listing.sort(function(a, b)
		{
			if (typeof a.items != 'undefined' && typeof b.items == 'undefined')
			{
				return -1;
			}
			else if (typeof a.items == 'undefined' && typeof b.items != 'undefined')
			{
				return 1;
			}
			else
			{
				if (a.name > b.name)
				{
					return 1;
				}
				else if (a.name < b.name)
				{
					return -1;
				}
				else
				{
					return 0;
				}
			}
		});
		
		var list = $('<ul />');
		for (var key in listing)
		{
			var item = listing[key];
			var listItem = $('<li />');
			listItem.data('path', item.path);
			if (typeof item.items != 'undefined')
			{
				if (depth != 1 && item.items.length > 0)
				{
					listItem.append('<h5>' + item.name + '</h5');
					listItem.append(generateList(item.items, depth - 1));
					listItem.addClass('directory');
					list.append(listItem);
				}
			}
			else
			{
				listItem.text(item.name);
				listItem.addClass('file');
				list.append(listItem);
			}
		}
		
		return list;
	};
});