var FormHandler  = new Class({
	Implements: Options,
	
	options: {
		format:'ul',
		cssclass:'error'
	},
	
	initialize: function(form, url, options){
    
		this.setOptions(options);

		this.form = form;
		this.url = url;
		this.showed_error_fields = [];
		
      this.form.addEvent('submit', function(ev){
        ev.stop();
        //distroy previous shown errors
        this.showed_error_fields.each(function(el){el.destroy()});
        this.showed_error_fields.empty();
    		ev.target.send();
  	  }.bindWithEvent(this));  
			
		this.form.set('send', {
			method: 'post', 
			url: this.url, 
			onSuccess: this.onSuccess.bind(this)
		});
    
  },
				
	onSuccess: function(responseText){
		response = new Hash(JSON.decode(responseText, true));
		message = response['message'];
		$('_global_errors').set('html',message);
		
		if (response['valid'] == "false") {
			form_errors = new Hash(response['form_errors']);
			form_errors.each(function(error, field_id){
				var ul_element = new Element(this.options.format, {
						  'id': field_id + '_error',
						  'class': this.options.cssclass
				});
				ul_element.inject($(field_id), 'after');
				
				error.each(function(error_message){
					var element = new Element('li');
					element.innerHTML += error_message;
					element.inject(ul_element);
				}.bind(this));
				
				this.showed_error_fields.include($(field_id + '_error'));
			}.bind(this));
		}
		else
		{
		  $$('#nl_subscriber ul').setStyle('display', 'none');
		}
	}
});

window.addEvent('domready', function() {
  new FormHandler(
    $(form_id),
		url, {
			cssclass:'error',
			format:'ul'
		}
	);
});
