var aSections = [];
var iCur = 0;

var btnPrev;
var btnNext;
var btnSubmit;
var btnSkipCoApp;

var msgError;

function validateSection ()
{
	sSec = aSections[iCur].getAttribute ('id');

	msgError.hide ();

	bValid = true;
	$$ ('#' + sSec + ' .required').each (function (e) {
		if ( e.getAttribute ('type') == 'checkbox' )
		{
			if ( e.checked == false )
			{
				e.addClassName ('invalid');
				bValid = false;
			}
		}
		else
		{
			if ( e.value == '' )
			{
				e.addClassName ('invalid');
				bValid = false;
			}
		}
	});

	if ( bValid == false )
		msgError.appear ();

	return bValid;
}

function showSection (iSec)
{
	if ( iSec > iCur )
	{
		if ( ! validateSection () )
			return false;
	}

	btnNext.show ();
	btnNext.disable ();
	btnPrev.disable ();
	btnSubmit.hide ();

	hideAllSections ();
	aSections[iSec].show ();
	iCur = iSec;

	if ( iSec < (aSections.length - 1) )
		btnNext.enable ();

	if ( iSec > 0 )
		btnPrev.enable ();

	if ( iSec == (aSections.length - 1) )
	{
		btnNext.hide ();
		btnSubmit.show ();
	}

	aInputs = aSections[iSec].select ('input');
	if ( aInputs.length > 0 )
		aInputs[0].focus ();
}

function prevStep ()
{
	showSection (iCur - 1);
}

function nextStep ()
{
	showSection (iCur + 1);
}

function hideAllSections ()
{
	$$('.section').each (Element.hide);
}

function submitForm ()
{
	bValid = validateSection ();

	if ( bValid )
	{
		btnSubmit.disable ();
	}

	return bValid;
}

Event.observe (window, 'load', function () {
	btnPrev = $('previous');
	btnNext = $('next');
	btnSubmit = $('submit');
	msgError = $('invalid-message');
	btnSkipCoApp = $('skipcoapp');

	btnSubmit.hide ();
	btnSkipCoApp.show ();
	btnNext.show ();
	btnPrev.show ();

	iCur = 0;

	aSections = $$('.section');
	showSection (iCur);

	$$ (['.input_text', '.input_select']).each (function (e) {
		e.observe ('focus', function () {
			msgError.hide ();
			this.removeClassName ('invalid');
		});
	});
});
