/**
 * Script: form.handler.js
 * Last update: May 16, 2008
 *
 * Options
 *  action url, url used for the POST or GET, default is form's action attribute value
 *  formValidation: default is true, requires form.validator.js
 *    formValidationErrors: where to place the error message (below, inline), default: below
 *    formValidation.specific.options (not yet implemented)
 *  aSync: default true, will use AJAX to send the form, else standard form submit
 *  onCompleteFunction
 *
 * Usage:
 *  var formHandler = new formHandler('myForm', {<options>});
 */
var formHandler = new Class({
  Implements: [Options, Events],

  options: {
    formValidation: true,
    validateLanguage: 'nl',
    formValidationErrors: 'below',
		validateOnly: false,
		clearFields: false,
    actionUrl: '',
    aSync: true,
		multiStep: false,
		multiPage: false,
		containingDivClass: null,
    onValidate: $empty,
    onComplete: $empty
  },

  initialize: function(whichForm, options) {
		this.setOptions(options);
    this.form = $(whichForm);
		this.actionUrl = this.form.get('action');
    this.fields = this.form.getElements('input');
    this.fields.extend(this.form.getElements('textarea'));
    this.response = this.form.getElement('.response');
    this.response.set('id', 'response-'+this.form.id);
		this.switching = false;

    this.form.addEvent('submit', function(e) {
      e.stop();
      this.send.delay(400, this);
    }.bind(this));

		this.form.addEvent('reset', function(e) {
			if (!confirm('Weet u zeker dat u het formulier wilt legen?\n Hierbij gaat alle ingevulde informatie verloren.')) {
      	e.stop();
			}
    }.bind(this));
		
		if(this.options.multiStep) {			
			this.steps = new Array;
			this.currentStep = 0;
			$$('#'+whichForm+' fieldset').each(function(step)
			{
				nextButton = step.getElement('input.next');
				if(nextButton != null) nextButton.addEvent('click', this.nextStep.bind(this));
				previousButton = step.getElement('input.previous');
				if(previousButton != null) previousButton.addEvent('click', this.previousStep.bind(this));
				//stepLegend = step.getElement('legend');
				//if(stepLegend != null) stepLegend.addEvent('click', this.legendActivateStep.bind(this));

				this.steps.include(step);
			}.bind(this));
			this.activateStep();
		}
		
    if (this.options.formValidation) {
      this.formValidator = new formValidator(this.form.id, {
        responseElement: this.response,
        validationErrors: this.options.formValidationErrors,
        responseElement: $(this.response.id),
				validateLanguage: this.options.validateLanguage
      });
    }
  },

  send: function() {
    new Fx.Scroll(window).toElement(this.response);

    if (this.options.formValidation && !this.formValidator.validateAllFields()) {
      return;
    }

		if (this.options.validateOnly) {
      this.fireEvent('onValidate');
      return;
		}
		
    if (!this.options.aSync) {
      this.form.submit();
      return;
    }

    var queryStr = this.form.toQueryString();

    this.fields.each(function(elm) {
      elm.set('disabled', 'disabled');
    });

    this.response.empty().addClass('ajaxloading');
		this.response.setStyle('visibility', 'visible');

    new Request.HTML({
      url: this.actionUrl,
      data: queryStr,
      method: 'post',
      update: this.response,
      onComplete: this.cleanUp.bind(this)
    }).send();
  },

  cleanUp: function() {
    this.response.removeClass('ajaxloading').addClass('complete');
    this.fields.each(function(elm) {
      elm.set('disabled', '');
    });
    if (this.options.clearFields) {
			this.form.reset();
		}
    this.fireEvent('onComplete');
  },
	
	legendActivateStep: function(e) {
		if(this.checkStepErrors())
		{
			if(!this.options.formValidation || this.formValidator.numOfErrors == 0)
			{
				step = e.target.getParent('fieldset');
				this.currentStep = this.steps.indexOf(step);
				this.activateStep();
			}
		}
	},
	
	nextStep: function() {
		if(!this.switching)
		{
			if(this.checkStepErrors())
			{
				if(!this.options.formValidation || this.formValidator.numOfErrors == 0)
				{
					this.currentStep++;
					this.switching = true;
					this.closeSteps();
					this.activateStep.delay(500, this);
				}
			}
		}
	},
	
	previousStep: function() {
		if(!this.switching)
		{
			this.formValidator.clearErrors();
			this.currentStep--;
			this.switching = true;
			this.closeSteps();
			this.activateStep.delay(500, this);
		}
	},
	
	checkStepErrors: function() {
		if(this.options.formValidation)
		{
			this.formValidator.clearErrors();
			activeStep = this.steps[this.currentStep];
			fields = activeStep.getElements('input, textarea');
			fields.each(function(field)
			{
				this.formValidator.validateField(field);
			}.bind(this));
		}
		return true;
	},
	
	closeSteps: function()
	{
		this.steps.each(function(step)
										{
											 parentDiv = step.getParent('div.'+this.options.containingDivClass);
											 if(parentDiv.hasClass('opendiv'))
											 {
												parentDiv.setStyle('height',parentDiv.scrollHeight);
											 }
											 parentDiv.morph('.'+this.options.containingDivClass);
											 parentDiv.removeClass('opendiv');
										 }.bind(this)
										);
	},
	
	activateStep: function() {
		step = this.steps[this.currentStep];
		parentDiv = step.getParent('div.'+this.options.containingDivClass);
		var myFx = new Fx.Tween(parentDiv,{onComplete: function()
																										{
																											parentDiv.setStyle('height','auto');
																											this.switching = false;
																										}.bind(this)});
		myFx.start('height', parentDiv.scrollHeight);
		parentDiv.addClass('opendiv');
	}
});