var current = 0
var max = 10;
var prefix = "quiz";
var tally = 0;
var score = [
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,0			
			];

function back() {
	if (current > 0) {
		hide(current);
		current--;
		show(current);
	}
}

function next() {
	if (current < max) {
		hide(current);	
		current++;
		show(current);
	}
}

function startover() {
	if (current > 0) {
		hide(current);
		current=0;
		show(current);
		
		inputs = $$(".chk");
		inputs.each( function(i) {
			$(i).style.backgroundPosition = '0 -40px';
		});	
		tally = 0;
		score = [
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,
			0,0,0,0,0,0			
			];		
		drawTally();
	}
}

function show(idx) {
	$(prefix+idx).style.visibility = 'visible';	
	showControl(idx);
	if(idx==0) {
		$('scoreboard').style.display = 'none';
	} else {
		$('scoreboard').style.display = 'block';	
	}
	if (idx < max) {
		$('total').style.display = 'none';
		$('totalbox').style.display = 'none';
	} else {
		showTotal();
	}
}

function showControl(idx) {
	if (idx==0) {
		$('control1').style.display = 'block';
		$('control2').style.display = 'none';
		$('control3').style.display = 'none';
	} else if (idx==10) {
		$('control1').style.display = 'none';
		$('control2').style.display = 'none';
		$('control3').style.display = 'block';	
	} else {
		$('control1').style.display = 'none';
		$('control2').style.display = 'block';
		$('control3').style.display = 'none';	
	}
}

function hide(idx) {
	$(prefix+idx).style.visibility = 'hidden';	
}

function track(evt) {
	elm = Event.element(evt);
	s = elm.id.indexOf('_');
	q = elm.id.substring(0,s);
	idx = q.substring(1);
	f = elm.href.indexOf('#');
	score[idx] = elm.href.substring(f+1);
	$(elm.id).style.backgroundPosition = '0 0';
	totalq = 3;
	if (idx==12) { totalq=4; }
	for(i=1;i<=totalq;i++) {
		ref = q+'_'+i;
		if (ref!=elm.id){
			$(ref).style.backgroundPosition = '0 -40px';
		}				
	}
	updateTally();
}

function updateTally() {
	tally = 0;
	score.each(function(s) {
		tally += new Number(s);
	});
	drawTally(tally);
}

function drawTally() {
	iconWidth = 22;
	totalWidth = 606;
	startLeft = 73;
	offset = tally*iconWidth/2;
	newWidth = totalWidth-offset;
	newLeft = startLeft + offset;
	$('cover').style.left = newLeft +'px';
	$('cover').style.width = newWidth +'px';
}

function showTotal() {
	if (tally < 15) {
		tp = 128;
	} else if (tally < 30) {
		tp = 199;
	} else if (tally < 52) {
		tp = 268;
	} else {
		tp = 335;
	}
	Element.update('total', 'Your total score<br />is ' + tally);
	$('total').style.top = tp +'px';
	$('total').style.display = 'block';		
	if (tally > 0) {
		$('totalbox').style.top = tp +'px';	
		$('totalbox').style.display = 'block';	
	}
}

window.onload = function() {
		inputs = $$(".chk");
		inputs.each( function(i) {
			Event.observe(i, 'click', track);
		});
}