// let's not clutter up the place with lots of globals.
var teafr = {};
teafr.path = null;
teafr.winner = null;
teafr.members = null;
teafr.ticks = 30;
teafr.smartArseComments = [
	"Biscuits are optional!",
	"Jump to it!",
	"Quick smart!",
	"When you're ready!",
	"Use the best china!",
	"Much appreciated."
];


//  ha'way!
$(document).ready(function() {

	// read the hash.
	var params = document.location.hash.split("/");
	if(params.length == 3) {
		$("input[name='username']").val(params[1]);
		$("input[name='list']").val(params[2]);
		teafr.path = params[1] + "/" + params[2];
		teafr.getMembers();
	}
	
	teafr.bindEvents();	
	teafr.listenOut();
	
});


teafr.listenOut = function() {
	
	var uri = "/listen/" + teafr.path;
	$.getJSON(uri, function(data){
			
		if(data.winner && data.winner !== null) {
			teafr.begin([data.winner]);
		} else {
			setTimeout(function(){
				teafr.listenOut();
			}, 1);			
		}
		
	});
	
};


// Add event listeners.
teafr.bindEvents = function() {
	
	// handle the form submit link
	$('#submit').click(function() {
		$(this).blur();
		teafr.getMembers();
		return false;		
	});
	
	// handle the form submit event
	$('#getMembers').submit(function(){
		teafr.getMembers();
		return false;
	});
	
	// Do the lucky dip.
	$('#start').live('click', function(){

		var btn = $('#start');
		btn.blur();
		if(btn.hasClass('disabled')) {
			return false;
		}

		// set a random start point and start animating.
		var count = $('li.member').length;
		var startPosition = Math.round(Math.random() * count);
		
		// teafr.path = $("input[name='username']").val() + "/" + $("input[name='list']").val();		
		$.post("/lodge/"+teafr.path+"?winner="+startPosition);

		// go.
		teafr.begin(startPosition);
		return false;
	});
	
};

teafr.begin = function(startPosition) {
	
	// modify the button.
	var btn = $('#start');
	if(btn.hasClass('disabled')) {
		return false;
	}
	btn.addClass('disabled').text("choosing at random");
	
	//clean up from last time.
	$('li.winner').removeClass('winner');
	$('#tweetout').remove();

	// set a random start point and start animating.

	teafr.winner = startPosition;
	teafr.members = $('li.member');
	teafr.tick(teafr.ticks);
};


// Retreave the members of the list from twitter.
teafr.getMembers = function() {

	teafr.path = $("input[name='username']").val() + "/" + $("input[name='list']").val();

	//update the page hash.
	document.location.hash = "#/" + teafr.path;

	// update the people display and status message.
	$('ol').slideUp();
	$('#people').slideUp(function(){
		$(this).html('grabbing your tea buddies from your twitter list...').slideDown();
	});

	// get the list members and add them to the display.
	var uri = "twitter/"+ teafr.path +"/members.json";
	$.getJSON(uri, function(data){
		var html = '';
		if(data.users && data.users.length > 0) {
			html = "<p><a href='#' id='start' class='button'>choose at random</a> from the "+data.users.length+" members of the list.</p>";
		} else {
			$('#people').html("There's nobody there. Do you need to go and make a <a href='http://twitter.com/lists'>list</a> on twitter?");
			return false;
		}
		$(data.users).each(function(index) {
			html += "<li class='member'><img src='"+this.profile_image_url+"'><h4>"+ this.name +"</a></h4><p><a href='http://twitter.com/"+this.screen_name+"' class='username'>@"+this.screen_name+"</a></p></li>";
		});
		
		// show the people.
		$('#people').slideUp(function(){
			$(this).html(html).slideDown();
		});
	});
};


// display the latest potential winner.
teafr.show = function(member) {
	$('li.hot-seat', '#people').removeClass('hot-seat');
	member.addClass('hot-seat');
};


// iterate through the ticks of the lottery.
teafr.tick = function(count) {
	var member = teafr.members.eq(teafr.winner);
	teafr.show(member);
	teafr.winner++;
	if(teafr.winner >= teafr.members.length) {
		teafr.winner = 0;
	}
	count--;
	if(count < 1) {
		teafr.done();
		return;
	}	
	var pause = 15 * (teafr.ticks - count);
	setTimeout(function(){
		teafr.tick(count);
	}, pause);
};


// display the winner.
teafr.done = function() {
	var winner = $('li.hot-seat', '#people');
	var smart = Math.round(Math.random() * (teafr.smartArseComments.length-1));
	var message = "Hey " +winner.find('a.username').text() + ", " + document.location.href +" says that it's your turn to put the kettle on! ("+ teafr.smartArseComments[smart] +")";	
	var tweetout = "<a id='tweetout' class='button' href='http://twitter.com?status="+escape(message)+"' target='_BLANK'>Tweet it!</a></div>";
	winner.addClass('winner').append(tweetout);
	$('#start').text("choose at random").removeClass('disabled');
	
	// cleanup the current lottery on the server
	$.post("/kill/"+teafr.path);
	
	teafr.listenOut();
}; 

