YUI.add('ContactForm', function(Y){

	/*
	 * ContactForm 
	 */
	function ContactForm(elementId){
		this.init(elementId);
	}
	
	ContactForm.prototype = {
		
		form: null, // YUI node for contact form
		formContainer: null, // container (div) for form, used for animation
		
		init: function(elementId){
			this.form = Y.one('#' + elementId);
			if(this.form){
				this.formContainer = this.form.get('parentNode');
				this.form.on('submit', this._sendForm, this);
				this._enableForm();
			}
		},
		
		// on submit handler for form
		_sendForm: function(event){
			this._disableForm();
			
			var url = this.form.get('action');
			Y.io(url, {
				method: 'POST',
				form: { id: this.form, useDisabled: true },
				
				context: this,
				headers: { 'X-Send-Method': 'XHR' },
				on: {
					success: this._formSubmitted,
					failure: function(){ alert('Het formulier kan helaas niet verstuurd worden.'); }
				}
			});
			event.preventDefault();
		},
		
		// on xhr success handler
		_formSubmitted: function(requestId, request){
			// 'hide' the form by making it transparant 
			var animation = new Y.Anim({
			        node: this.formContainer,
			        to: { opacity: 0.25 },
			        duration: 0.5
			});
			animation.on('end', function(){
				this._showThankYouMessage();
			}, this);
			animation.run();
		},
		
		_disableForm: function(){
			this.form.all('*').set('disabled', true);
		},

		_enableForm: function(){
			this.form.all('*').set('disabled', false);
		},
		
		_resetForm: function(){
			this._enableForm();
			this.form.reset();
			this.formContainer.setStyle('opacity', 1);
		},
		
		_showThankYouMessage: function(){
		    this.overlay = new Y.Overlay({
		        width:"24em",
		        centered: this.form,
		        bodyContent: "<p>Uw bericht is succesvol verzonden.</p>" +
		        	"<p style='font-size: 80%; color: gray'><a href='#'>Klik hier om dit venster te sluiten</a></p>",
		        zIndex:2
		    });
		    this.overlay.render();
		    this.overlay.on('click', function(event){
		    	this.overlay.destroy();
		    	this._resetForm();
		    	event.preventDefault();
		    }, this);
		}
		
	};
	
	Y.ContactForm = ContactForm;
	
}, '0.1', { requires: ['node', 'io', 'event', 'anim', 'overlay'] });

