var aligns = ['left','center','right']; // randomly pick alignments
var sexts = [];
var offset = 0;
var getting = false;

$(document).ready(function() {
	fadeIn();
    
    // override click handling for the voting links
    $('#votelinks a').click(function(e) {
    	e.preventDefault();
    	var val = this.id;
    	vote(val);
    });
});

function fadeIn() {
	// pick a random alignment
    var al = aligns[Math.floor(Math.random()*3)];
    $('#message').css('text-align', al);
    $('#credit').css('text-align', al);

    // keep the sexts queue full
    if (sexts.length < 3) {
    	getSexts();
    }

    if (sexts.length > 0) {
    	// get a sext off the queue and display it
    	sext = sexts.shift();
    	$("#messageid").text(sext.id);
    	$("#message").text(sext.message);
    	$("#credit").text(sext.credit);
    	
    	// reset the vote links
    	$('#votelinks').show();
    	$('#voteresult').text('');
    	
    	// and do the fade in
    	$('#heightkeeper').css('height', $('#fadeblock').css('height'));
    	$('#fadeblock').fadeIn(1500, function() {
    		setTimeout('fadeOut()', 3000);
    	});
    }
    else {
    	// if no sexts on the queue, we just try again in 500 ms
    	setTimeout('fadeIn()', 500);
    }
}

function getSexts() {
	if (getting == false) {
		getting = true;
		$.get('fetch.php', {n:10, o:offset}, function(data) {
			var added = 0;
			offset += 10;
			var lines = data.split("\n");
			while (lines.length >= 3) {
				added++;
				sexts.push({'message':lines.shift(),
					'credit':lines.shift(),
					'id':lines.shift()
				});
			}
			getting = false;
			
			if (added < 10) {
				offset = 0;
			}

            
		});
	}
}

function fadeOut() {
    $('#fadeblock').fadeOut(1500, function() {
        fadeIn();
    });
}

function vote(str) {
	var value = (str == 'voteup') ? 'up' : 'down';
	var id = $('#messageid').text();
			
	$.get('vote.php', {'id':id, 'value':value}, function(data) {
		if ($('#messageid').text() == id) {
			$('#votelinks').hide();
			$('#voteresult').text(data);
		}
		else {
			// vote.php lagged out, don't show any feedback
		}
	});
}

