var NewsletterForm = new Class({
	Implements: [Options, Events, Log],
	
	// Variables
	element: null,
	form: null,
	application: null,

	// Class instances
	
	initialize: function( element )
	{
		//this.enableLog();
		//this.disableLog();
		this.log("NewsletterForm::initialize()");

		// Set variables
		this.element = element;
		this.application = new Application();

		this.initForm();
	},

	/*
	 * Init form
	 */
	initForm: function()
	{
		this.log("NewsletterForm::initForm()");

		var requestUrl = this.application.getConfig().requestPath.newsletter;

		var handlers = {
			onRequest: function()
			{
				//this.log("onRequest");

			}.bind(this),
			onSuccess: function(response)
			{
				this.log("response.success: "+ response.success);

				if(response.success)
				{
					this.log("succes!");
					
					// Track event
					this.application.trackEvent('newsletter', 'success', this.application.page.name);

					this.log("response.email: " + response.email);

					this.form.hide();

					//this.form.formValidMessage.container.getElement('.email').set('text', response.email);

					this.form.formValidMessage.show();
					this.form.reset();
				}
				else
				{
					this.log("error!");

					// Track event
					this.application.trackEvent('newsletter', 'error', this.application.page.name);
					
					this.form.formErrorMessage.clear();
					this.form.formErrorMessage.addMessage('email', 0, response.error);
					this.form.formErrorMessage.show();
				}
			}.bind(this),
			onFailure: function(xhr)
			{
				this.log("onFailure");
				
				// Track event
				this.application.trackEvent('newsletter', 'fail', this.application.page.name);
				
				this.form.formErrorMessage.clear();
				this.form.formErrorMessage.addMessage('email', 0, "Verzenden mislukt");
				this.form.formErrorMessage.show();
			}.bind(this)
		};

		var options = {
			showLoader: true,
			allowStatus: true,
			formErrorMessage: {
				allow: true,
				container: this.element.getElement('.form-message-container'),
				allowClose: false
			},
			formValidMessage: {
				allow: true,
				container: this.element.getElement('.form-message.valid'),
				allowClose: false
			}
		};

		var emailOptions = {};
		emailOptions.hintText = "Vul hier je e-mail adres in...";

		var form = new JsonForm($('newsletter-form'), requestUrl, handlers, options);
		
		var emailElement = new FormElement(form, 'email', emailOptions);
		emailElement.addValidation(Form.REGEX_EMAIL, 'Vul een geldig e-mailadres in');
		form.addElement(emailElement);

		// Add buttons
		var submitButton = new FormSubmitButton(form, '.button', {showLoader: true});
		form.addButton(submitButton);

		// Save form
		this.form = form;

		this.form.addEvent('onSubmit', function() {

			this.log("onSubmit");

			// Track event
			this.application.trackEvent('newsletter', 'submit', this.application.page.name);

			this.form.formErrorMessage.clear();

		}.bind(this));

	}

});
