var ProductWizard = Class.create(
{
	initialize: function(element)
		{
		this.element = element;
		this.findForm();
	},

	findForm: function()
		{
		this.form = this.element.select('form')[0];
		this.form.wizard = this;
		var buttonPressed = this.form.select('input.buttonPressed')[0];
		var next = this.form.select('input.next')[0];
		if (next)
		{
			next.observe('click', function()
				{
				buttonPressed.value = 'next';
			});
		}
		var previous = this.form.select('input.previous')[0];
		if (previous)
		{
			previous.observe('click', function()
				{
				buttonPressed.value = 'previous';
			});
		}
		var finish = this.form.select('input.finish')[0];
		if (finish)
		{
			finish.observe('click', function()
				{
				buttonPressed.value = 'finish';
			});
		}
	},

	reset: function()
		{
		var params = this.getUriParams();
		delete params['path'];
		delete params['previousAnswers'];
		delete params['answer'];
		delete params['buttonPressed'];
		delete params['next'];
		delete params['previous'];
		this.setUriParams(params);
	},

	submit: function()
		{
		var parameters = this.form.serialize(true);
		parameters.chain = this.element.id;
		parameters.useFile = ProductWizard.useFile;
		this.addUriParams(parameters);
	},

	getUriParams: function()
		{
		var location = document.location.href;
		var questionIndex = location.indexOf('?');
		if (questionIndex < 0)
			return {};
		else
			return location.substring(questionIndex + 1).toQueryParams();
	},

	setUriParams: function(params)
		{
		var location = document.location.href;
		var poundIndex = location.indexOf('#');
		if (poundIndex >= 0)
			location = location.substring(0, poundIndex);
		var questionIndex = location.indexOf('?');
		if (questionIndex >= 0)
			location = location.substring(0, questionIndex);

		document.location.href = location + '?' + $H(params).toQueryString();
	},

	addUriParams: function(params)
		{
		var existingParams = this.getUriParams();
		Object.extend(existingParams, params);
		this.setUriParams(existingParams);
	}
});
ProductWizard.submit = function(event, form)
	{
	event.stop();
	form.wizard.submit();
	return false;
};

document.observe('dom:loaded', function()
	{
	$$('.productWizard').each(function(element)
		{
		new ProductWizard(element);
	});
});

