var Contact = {
	
	init: function() {
		
		new Element( 'input', {
			'type': 'hidden',
			'name': 'ajax',
			'value': '1'
		} ).inject( 'contactForm', 'top' );
		
		this.instance = new Form( 'contactForm', {
			override: true,
			validate: {
				'from_name': [
					/([a-zA-Z])+( )+([a-zA-Z])+/,
					'Please provide your full name.'
				],
				'from_email': [
					/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
					'Please provide your email address.'
				],
				'message': [
					/.+/,
					'Please provide a message.'
				],
				'captcha': [
					/.+/,
					'Please provide the verification key.'
				]
			},
			onStart: this.onStart.bind( this ),
			onError: this.onError.bind( this ),
			onReset: this.onReset.bind( this ),
			onComplete: this.onComplete.bind( this )
		} );
		
		this.captchaSrc = $( 'captchaText' ).get( 'src' );
		
	},
	
	toggleLoading: function( action, form ) {
		action = $chk( action ) ? action : 'hide';
		image = form.getElement( 'p[class=submit] img' );
		
		if( action == 'hide' )
			image.setStyle( 'display', 'none' );
		else
			image.setStyle( 'display', '' );
	
	},
	
	onStart: function( form ) {
		this.toggleLoading( 'show', form );
	},
	
	onError: function( form ) {
		this.toggleLoading( 'hide', form );
	},
	
	onReset: function( form ) {
		this.toggleLoading( 'hide', form );
	},
	
	onComplete: function( form ) {
		
		new Request.HTML( {
			url: form.get( 'action' ),
			onSuccess: this.onRequestComplete.bind( this )
		} ).post( form );
		
		this.form = form;
	
	},
	
	onRequestComplete: function( a, b, c ) {
		
		this.toggleLoading( 'hide', this.form );
		
		var response = new Element( 'div', { 'html': c } );
		var type = response.getElement( 'type' ).get( 'text' );
		var title = response.getElement( 'title' ).get( 'text' );
		var message = response.getElement( 'message' ).get( 'text' );
		
		if( type == 'success' ) {
			
			this.form.disable();
			
			var success = new Element( 'div', {
				'class': 'formSuccess',
				'styles': {
					'opacity': 0
				},
				'html': '<h1>'+ title +'</h1><p>'+ message +'</p>'
			} ).inject( document.body, 'top' ).centerOn( this.form );
			
			success.fade( 'in' );
		
		} else {
			
			var error = new Element( 'p', {
				'class': 'error',
				'text': message
			} );
			
			$( 'errorMessage' ).empty().adopt( error );
			
			this.instance.enableForm();
			this.refreshCaptcha();
		
		}
		
	},
	
	refreshCaptcha: function() {
		$( 'captchaText' ).set( 'src', this.captchaSrc +'/'+ Math.random() );
	}
	
};

window.addEvent( 'domready', Contact.init.bind( Contact ) );