var currentItem = 0;
var totalCount = 0;
var slides = new Array();
var pollUrl = '';

function jumpTo(item) {
	if (item < 0 || item >= slides.length) {
		return;
	}
	
	Element.hide(slides[currentItem]);
	
	if (item == 0) {
		$('previous').href = pollUrl;
		$('previous').title = '在新窗口打开完整调查页面';
		$('previous').innerHTML = '完整版本';
		$('previous').target = '_blank';
		Element.show('next');
		$('next').title = '';
		$('next').innerHTML = '开始答题';
	}
	
	if (item == 1) {
		if (currentItem == 0) {
			pollUrl = $('previous').href;
		}
		$('previous').href = 'javascript:previous()';
		$('previous').title = '说明';
		$('previous').innerHTML = ' &laquo; 说明';
		$('previous').target = '';
		$('next').title = '';
		$('next').innerHTML = '下一题 &raquo; ';
		Element.show('next');
	}
	
	if (item == 2) {
		$('previous').title = '上一题';
		$('previous').innerHTML = ' &laquo; 上一题';
		Element.show('next');
	}
	
	if (item == slides.length - 1) {
		// the last frame
		Element.hide('next');
		Element.show('submit-button');
	}
	
	if (item > 0 && item < slides.length - 1) {
		Element.show('previous');
		Element.show('next');
	}
	
	if (item > 0) {
		$('progress').update(item + '/' + (slides.length - 1)).show();
	} else {
		$('progress').hide();
	}
	
	Element.show(slides[item]);
	
	currentItem = item;
}

function next() {
	jumpTo(currentItem + 1);
}

function previous() {
	jumpTo(currentItem - 1);
}

function initPoll() {
	slides[0] = $('desc');
	
	var questions = $('wrapper').select('div[class="question"]');
	for (var ii = 0; ii < questions.length; ii++) {
		var question = questions[ii];
		slides[ii + 1] = question;
	}
	
	var height = $('wrapper').getHeight();
}

function checkAnswer() {
	var form = $('answer-form');
	var questionIds = $('question-ids').innerHTML.split(',');
	for (var ii = 0; ii < questionIds.length; ii++) {
		var options = eval('form.Q' + questionIds[ii]);
		checked = false;
		for (var jj = 0; jj < options.length; jj++) {
			if (options[jj].checked) {
				checked = true;
				break;
			}
		}
		if (!checked) {
			alert('第' + (ii + 1) + '题你还没选择答案呢');
			jumpTo(ii + 1);
			return false;
		}
	}
	
	new Ajax.Updater(
		'wrapper',
		'/poll.do?method=submit',
		{
			method: 'post',
			parameters: Form.serialize('answer-form')
		}
	);
	
	return false;
}