/* Execute upon DOM LOAD */
$(document).ready(function(){
	/* LOAD widget data */
	$.getJSON("http://chch.davesblog.ch/teilnehmerliste2/load.php",function(data){
		if(data.error)
		{
			/* If there is an error, output and exit */
			$(".content_tn").html(data.error);
			return false;
		}
		$(".content_tn .fans").html('');
		/* Remove the rotating GIF */
		$.each(data.members,function(i,val){
			/* Loop through all the shown members and add them to the .content DIV */
			$(".content_tn .fans").append('<a href="http://twitter.com/'+i+'" target="_blank"><img src="'+val+'" width="48" height="48" title="'+i+'" alt="'+i+'" /></a>');

		});
		$('#counter').html(data.membersCount);
		/* Set the member counter */
		$('.fanPageLink').attr('href',data.fanPage+'/members').attr('target','_blank');
		/* Set the .fanPageLink-s to point to the profile page */
	});

	$('.joinFP').click(function(e){
		
		/* IF the green button has been clicked.. */
		
		if($('.content_tn').html().indexOf('id="mask"')!=-1)
		{
			/* ..and the form is already shown exit */
			e.preventDefault();
			return false;
		}

		/* ..in the other case, start a fade out effect */
		$(".content_tn .fans").fadeOut("slow",function(){
			$('.content_tn').append('<div id="mask">\
			Damit du in der offiziellen Teilnehmerliste erscheinst musst du hier einfach deinen Twitternamen eingeben.\
			<label>Dein Twittername:</label>\
			<input id="twitterName" name="twitter" type="text" size="20" />\
			<a href="" class="greyButton" onclick="sendData();return false;">Teilnehmen!</a> oder <a href="#" onclick="cancel();return false;">abbrechen</a>\
			<div id="response"></div>\
			</div>');
			
		});
		
		/* Prevent the link from redirecting the page */
		e.preventDefault();
	});
});
function sendData()
{
	/* This function sends the form via AJAX */
	$('#response').html('<img src="img/loader.gif" />');
	var twitter = $('#twitterName').val();
	if(!twitter.length)
	{
		$('#response').html('<span style="color:red">Bitte deinen Twitternamen eingeben.</span>');
		return false;
	}
	$.ajax({
		type: "POST",
		url: "http://chch.davesblog.ch/teilnehmerliste2/add.php",
		data: "twitter="+encodeURIComponent(twitter),
		/* Sending the filled in twitter name */
		success: function(msg){
			/* PHP returns 1 on success, and 0 on error */
			var status = parseInt(msg);
			if(status)
			{
				$('#response').html('Toll, dass du auch mitmachtst! Du wirst in wenigen Minuten hizugef&uuml;gt.<br /><a href="#" onclick="cancel();return false">Formular ausblenden</a>.');
				$('#twitterName').val('');
			}
			else
			$('#response').html('<span style="color:red">Sorry. Es gibt keinen Twitterer mit diesem Namen.</span>');
			
		}
	});
}
function cancel()
{
	/* Hides the "Join" form */
	$('#mask').remove();
	$('.content_tn .fans').fadeIn('slow');
}
