

var ContactManager = Class.create({
	
	contact_form: null,
	options: null,
	noticeTimeoutID: null,
	
	initialize: function( form, options )
	{
		this.contact_form = $(form);
		if ( this.contact_form.tagName.toLowerCase() != 'form' )
			throw ( "The form ID you specified doesn'd correspond to a form element" );
		
		this.options = Object.extend({
			noticeID: 'notice'
		}, options || {});
		
		this.addBehaviors();
	},
	
	send: function()
	{
		var inputs, errors = [];
		// Form validation:
		inputs = this.contact_form.getElements();
		$A(inputs).each( function(input) {
			if ( input.getAttribute('name').substr(-2,2) == '_1' ) {
				var originalValue = input.tagName.toLowerCase() == 'textarea' ? input.innerHTML : input.getAttribute('value');
				if ( input.getValue() == originalValue )
					errors.push( "Vous devez remplir le champ '"+originalValue+"'" );
			}
		});
		if ( errors.length ) {
			this.notify( errors.join('<br />') );
			return false;
		}
		
		this.contact_form.request({
			onComplete: function( transport, json ) {
				var msg = ( (json && json.message) ? json.message : transport.responseText );
				var success = ( (json && json.success) ? json.success : false );
				
				this.notify(msg);
				
				if ( success ) this.contact_form.reset();
				this.contact_form.enable();
			}.bind(this)
		});
		this.contact_form.disable();
	},
	
	notify: function( content )
	{
		var notice = $(this.options.noticeID);
		if ( !notice ) return false;
		
		clearTimeout( this.noticeTimeoutID );
		notice.update( content );
		
		if ( notice.visible() )
			new Effect.Pulsate(notice, {duration:1.5, pulses:3, queue:'end'});
		else
			new Effect.Appear(notice);
		
		this.noticeTimeoutID = setTimeout( function() { new Effect.Fade(notice); }, 20*1000 );
	},
	
	addBehaviors: function()
	{
		// Form behavior:
		this.contact_form.observe('submit', function() {
			this.send();
		}.bindAsEventListener(this));
		this.contact_form.onsubmit = function() {return false;};
		
		// Input behaviors:
		var inputs = this.contact_form.getElements();
		$A(inputs).each( function( input ) {
			if ( input.tagName.toLowerCase() == 'textarea' || ( input.tagName.toLowerCase() == 'input' && input.readAttribute('type') == 'text' ) ) {
				var originalValue;
				switch ( input.tagName.toLowerCase() )
				{
					case 'textarea':
						originalValue = input.innerHTML;
						break;
						
					default:
						originalValue = input.getAttribute('value');
						break;
				}
				input.observe( 'focus', function() {
					if( input.getValue() == originalValue ) input.setValue('');
					$(this).addClassName('focus');
				});
				input.observe( 'blur', function() {
					if ( input.getValue() == '' ) input.setValue( originalValue );
					$(this).removeClassName('focus'); 
				});
			}
		});
	}
});

var contactManager;
Event.observe( window, 'load', function() { contactManager = new ContactManager('contact_form'); } );
