$(document).ready(function()
{
	// Apply collapsable
	$('.collapsable').collapsable();

	// Apply ajax search
	$('.ajax-search input').each(function()
	{
		var self    = $(this);
		var url     = self.attr('rel');
		var list    = $('table.listing');
		var pages   = $('p.pagination');

		// Make sure the junk is there
		if (url && list.length)
		{
			self.change(function()
			{
				// Turn spinner on
				self.addClass('loading');

				$.get(url, {q: self.val()}, function(data)
				{
					// Remove pagination
					pages.html('');

					// Replace the list with the result
					list.replaceWith(data);

					// Re-query the listing
					list = $('table.listing');

					// Turn spinner off
					self.removeClass('loading');
				});
			});
		}
	});

	// Fancy multi-select functionality
	$('table#many-select').each(function()
	{
		var self = $(this);
		var copy = $('table#many-copy tr:first');
		var add  = self.find('a[href="#add"]');

		if (copy.length && add.length)
		{
			var remove_row = function()
			{
				// Drop the row from the table
				$(this).parents('tr').remove();
				// Prevent normal action
				return false;
			};

			// Bind removal
			self.find('a[href="#delete"]').click(remove_row);
			copy.find('a[href="#delete"]').click(remove_row);

			add.click(function()
			{
				// Insert the row before the add row
				copy.clone(true).insertBefore(self.find('tr.add'));
				// Prevent normal action
				return false;
			});
		}
	});
});
