jQuery(document).ready(function(){
/* Executed on DOM load */

	var data = { action: "kohana_ajax", controller: "twitter/index" };
	jQuery.post("/wp-admin/admin-ajax.php", data, function(data){
		/* Loading the widget data */
		if(data.error)
		{
			/* If there is an error, output and exit */
			jQuery(".content").html(data.error);
			return false;
		}
		
		jQuery(".content .fans").html('');
		/* Remove the rotating GIF */

		jQuery.each(data.members,function(i,val){
			/* Loop through all the shown members and add them to the .content DIV */
			jQuery(".content .fans").append('<a href="http://twitter.com/'+i+'" target="_blank"><img src="'+val+'" width="48" height="48" title="'+i+'" alt="'+i+'" /></a>');

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

	jQuery('.joinFP').click(function(e){
		
		/* IF the green button has been clicked.. */
		
		if(jQuery('.content').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 */
		jQuery(".content .fans").fadeOut("slow",function(){
			
			jQuery('.content').append('<div id="mask">\
			Что-бы присоединиться к списку друзей на твитере, просто введите своё имя.\
			<label>Учётная запись твитера:</label>\
			<input id="twitterName" name="twitter" type="text" size="20" />\
			<a href="" class="greyButton" onclick="sendData();return false;">Отослать!</a> или <a href="#" onclick="cancel();return false;">отменить</a>\
			<div id="response"></div>\
			</div>');
			
		});
		
		/* Prevent the link from redirecting the page */
		e.preventDefault();
	});
});

function sendData()
{
	/* This function sends the form via AJAX */
	
	jQuery('#response').html('<img src="http://static.telestrekoza.com/images/loading.gif" />');
	
	var twitter = jQuery('#twitterName').val();
	
	if(!twitter.length)
	{
		jQuery('#response').html('<span style="color:red">Пожалуста заполните данные о Вашей учётной записи.</span>');
		return false;
	}
	
	var data = { action: "kohana_ajax", controller: "twitter/add", twitter: encodeURIComponent(twitter) };
	jQuery.post("/wp-admin/admin-ajax.php", data, function(msg){
			/* PHP returns 1 on success, and 0 on error */
			var status = parseInt(msg);
			if(status)
			{
				jQuery('#response').html('Спасибо за то что Вы к нам присоединились. Данные обновлятся через несколько минут.<a href="#" onclick="cancel();return false">Вернуться к обычному виду</a>.');
				jQuery('#twitterName').val('');
			}
			else
			jQuery('#response').html('<span style="color:red">На твитере нет такого пользователя.</span>');
			
		});
}

function cancel()
{
	/* Hides the "Join" form */
	jQuery('#mask').remove();
	jQuery('.content .fans').fadeIn('slow');
}