var BIG_FAT_GLOBAL_COMPLAINT_ID = null;
var OMG_BIG_GAT_GLOBAL_TIMEOUT_ID = null;

var kvetch = {
	timerID: null,
	complaintID: null,
	init: function() {
		$('#a').click(kvetch.voteUp);
		$('#b').click(kvetch.reload);
		$('#c').click(kvetch.voteDown);
		
		kvetch.refresh();
	},
	/**	=====================================================
		VOTE FUNCTIONS
	*/
	vote:function(dir) {		
		$.post("/votes/",
          {complaint_id: kvetch.complaintID,
          vote: dir},
          function(data){}, "json");
		kvetch.refresh();
	},
	voteUp: function() {
		$('#b span').removeAttr('class').addClass('a').show().fadeOut(1000);
		kvetch.vote('no');
	},
	voteDown: function() {
		$('#b span').removeAttr('class').addClass('c').show().fadeOut(1000);
		kvetch.vote('yes');
	},
	reload:function() {
		$('#b span').removeAttr('class').addClass('b').show().fadeOut(1000);
		kvetch.refresh();
	},
	/**	=====================================================
		REFRESH
	*/	
	refresh: function() {
		//	Show the latency feedback mechanism, lock
		//	voting (we don't want users thinking they're
		//	voting for the wrong complaint)
		kvetch.controls.lock();
		$("#loading:hidden").fadeIn(400);
		$("#complaint").fadeOut(400, function(){
			 $.getJSON(
					"/complaints/?format=json",
			        function(data){
						$("#loading:visible").fadeOut(200);
						$("#complaint").text(data.complaint.body).each(function(){
							// fix the position before fading in.
							this.style.marginTop = (-1 * (Math.floor($(this).height()/2)) + 'px');
						}).fadeIn(600);
						kvetch.complaintID = data.complaint.id;
						kvetch.resetTimer();
						kvetch.controls.unlock();
					}
				);	
		});
	   
	},
	resetTimer: function() {
		clearTimeout(kvetch.timerID);
		kvetch.timerID = setTimeout(kvetch.refresh, 10 * 1000);
	},
	controls: {
		lock: function() {},
		unlock: function() {}
	}
}

// let's get the ball rolling
$(document).ready(kvetch.init);

