$(document).ready(prepareLiveLinks);

function prepareLiveLinks()
{
	$('#livedatetable a').each(function()
	{
		var linkId = $(this).attr('id');
		var linkInfo = linkId.split('_');
		var linkType = linkInfo[0];
		var liveDateId = linkInfo[1];

		if (linkType == 'going' || linkType == 'notgoing')
		{
			$(this).click(function()
			{
	 			replaceLink(this);
				changeGoing(linkType, liveDateId);
			}).removeAttr('href').addClass('jslink');
		}
	});
}

function changeGoing(choice, liveDateId)
{
	if (choice == 'going')
	{
		choice = 'go';
	}
	else
	{
		choice = 'not';
	}

	$.ajax(
	{
		url: '/live.php?xml=1&' + choice + '=' + escape(liveDateId),
		type: 'GET',
		datatype: 'xml',
		timeout: 10000,
		error: function()
		{
			$('#wait').text("Error");
		},
		success: function(xml)
		{
			var waitParent = $('#wait').parent();
			$('#wait').remove();
			$(xml).find('response').each(function()
			{
				var liveDateId = $(this).attr('itemId');
				var type = $(this).attr('nextType');
				var text = '';
				var onclick = '';
				if (type == 'going')
				{
					text = "I'm going to this!";
				}
				else
				{
					text = "I'm not going anymore";
				}
				$('<a></a>').attr('id', type)
					.addClass('jslink').text(text).click(function()
					{
						replaceLink(this);
						changeGoing(type, liveDateId);
					}).appendTo($(waitParent));
			});
		}
	});
}

function replaceLink(link)
{
	var linkParent = $(link).parent();
	$(link).remove();
	linkParent.append($('<span></span>').attr('id', 'wait').text('Please Wait...'));
}

