var OCContactForm = Class.create();
OCContactForm.prototype =
{
	initialize : function (which_form)
	{
		if (!which_form)
		{
			which_form = 'contact_submit';
		}
		this.form = $(which_form);
		this.form.obj = this;
		// find the submit button
		var inputs = Form.getInputs(this.form, 'submit');
		this.submit_button = inputs[0];
		Event.observe(this.form, 'submit', this.generateSig.bindAsEventListener(this));
		this.consultIdCookie();
	},
	
	generateSig : function (e)
	{
		Event.stop(e);
		if (this.form.elements['message'].value == '')
		{
			alert('You forgot to say anything!');
			return;
		}
		this.submit_button.disabled = 'disabled';
		if (!this.form.elements['nonce'])
		{
			// must be an admin
			this.submitCallback();
			this.submit_button.disabled = '';
		}
		// fetch a nonce
		new Ajax.Request(
			'/speak/nonce.txt',
			{
				method : 'get',
				onSuccess : this.generateSigProper.bind(this),
				onFailure : this.generateSigFail.bind(this),
				onException : this.generateSigException.bind(this)
			});
	},
	
	generateSigProper : function (transport)
	{
		var nonce = transport.responseText;
		this.form.elements['nonce'].value = nonce;
		var message = this.form.elements['message'].value.replace("\r", '');
		var sig = hex_sha1(nonce+message+(hex_sha1(nonce+message)));
		this.form.elements['sig'].value = sig;
		// really submit the form
		this.submit();
	},
	
	generateSigFail : function (transport)
	{
		alert('Sorry, there was a (hopefully temporary) problem submitting your post. '+
			'Please try again later.');
		this.submit_button.disabled = '';
	},
	
	generateSigException : function (transport, e)
	{
		alert('exception: '+e.getMessage());
		this.submit_button.disabled = '';
	},
	
	submit : function ()
	{
		this.setIdCookie();
		if (!this.submitCallback)
		{
			this.form.submit();
		}
		else
		{
			this.submitCallback();
			this.submit_button.disabled = '';
		}
	},
	
	setIdCookie : function ()
	{
		var name = this.form.elements['name'].value;
		var email = this.form.elements['email'].value;
		if (name.length)
		{
			document.cookie = 'name='+escape(name);
		}
		if (email.length)
		{
			document.cookie = 'email='+escape(email);
		}
	},
	
	consultIdCookie : function ()
	{
		var cookies = document.cookie;
		var pos = cookies.indexOf("name=");
		if (pos != -1)
		{
			var end = cookies.indexOf(";", pos);
			if (end == -1)
			{
				end = cookies.length;
			}
			var name = cookies.substring(pos+5, end);
			this.form.elements['name'].value = name;
		}
		pos = cookies.indexOf("email=");
		if (pos != -1)
		{
			var end = cookies.indexOf(";", pos);
			if (end == -1)
			{
				end = cookies.length;
			}
			var email = cookies.substring(pos+6, end);
			this.form.elements['email'].value = email;
		}
	}
};
