var Form = new Class({
	form: null,
	initialize: function(form, thanks) {
		this.form = form;
		this.thanks = thanks;
		this.attach();
	},
	attach: function() {
		this.form.addEvent('submit', this.submit.bindWithEvent(this));
		this.form.getElements('input,textarea').addEvent('focus', this.attachFields.bindWithEvent(this));
	},
	getFields: function() {
		var fields  = this.form.getElements('input,textarea');
		var results = {};
		for (var i=0; i<fields.length; i++) {
			results[fields[i].get('name')] = fields[i].get('value');
		}
		return results;
	},
	attachFields: function(e) {
		var value = e.target.get('value').trim();
		if (value == 'Name' || value == 'Phone or email' || value == 'Comment:') {
			e.target.set('value', '');	
		}
	},
	submit: function(e) {
		e.stop();
		var request = new Request.JSON({
			url: this.form.get('action'),
			onSuccess: this.onSuccess.bind(this),
			onFailure: this.onFailure.bind(this)
		}).post(this.getFields());
	},
	onSuccess: function(response) {
		if (response.error == false) {
			this.form.reset();
			this.form.tween('left', 300);
			if (this.thanks) this.thanks.tween('left', 0);
		} else {
			alert(response.error + '!');	
		}
	},
	onFailure: function() {
		alert('Submission request failed. Please try again.');
	}
});

document.addEvent('domready', function() {
	if ($('form_contact')) {
		var form = new Form($('form_contact'), $('form_contact_thanks'));
	}
});
