var set;
var top_ids = '';

$(document).ready(function() {
	$('#left').click(function() { if(set) change_set('/ajax/get_set/' + set.prev); return false; });
	$('#right').click(function() { if(set) change_set('/ajax/get_set/' + set.next); return false; });
	$('.star-rating a').click(function() { if(set) change_set('/ajax/set/'+set.id+'/'+$(this).html()); return false; });
	$('#top a').each(function() { top_ids += this.href.substring(this.href.indexOf('#')); return false; });
	setTimeout(function() { $.getJSON('/ajax/top/'+(new Date()).getTime(), null, on_top_updated); }, 15000);

	if(location.hash.substring(1) > 0)
		change_set('/ajax/get_set/' + location.hash.substring(1));
	else {
		if($('#start_id'))
			change_set('/ajax/get_set/' + $('#start_id').html());
		else
			change_set('/ajax/get_next_set');
	}

	setInterval(poll, 500);
});

function change_set(url) {
	set = null; 
	$.getJSON(url + '/' + (new Date()).getTime(), null, on_set_updated);
	return false;
}

function on_set_updated(s) {
	location.hash = '#' + s.id;
	set = s;
	$('#preload').html(s.data);
	$('#set').fadeOut(700, function() { $('#set').html($('#preload').html()); $('#set').fadeIn(700); } );

	$('#user').parent().html($('#user').css('width', ((s.rating.user * 20) ? (s.rating.user * 20) : 0) + '%').parent().html());
	$('.star-rating a').click(function() { if(set) change_set('/ajax/set/'+set.id+'/'+$(this).html()); return false; });
	$('#average').parent().html($('#average').css('width', ((s.rating.average * 20) ? (s.rating.average * 20) : 0) + '%').parent().html());

	if(s.prev == false)
		$('#left').hide();
	else
		$('#left').show();

	$('#pic_num').html(s.id);
	$('#perm').val('http://'+location.host+'/#'+s.id);
	$('#hidid').val(s.id);

	if(s.next == false)
		$('#right').hide();
	else
		$('#right').show();
}

function on_top_updated(t) {
	if(t.ids != top_ids) {
		top_ids = t.ids;
 		$('#top_images').fadeOut(700, function() { $('#top_images').html(t.html).fadeIn(700); } );
	}
	setTimeout(function() { $.getJSON('/ajax/top/'+(new Date()).getTime(), null, on_top_updated); }, 15000);
}

function poll() {
	if(location.hash.length > 1 && (set != null && location.hash.substring(1) != set.id)) {
		change_set('/ajax/get_set/' + location.hash.substring(1));
	}
}