var contactHandler = Class.create();
contactHandler.prototype = {

  form: null,
  url: '/',

  initialize: function(form) {
    this.form = $(form);
    this.url = this.form.readAttribute('action');
    Event.observe(this.form, 'submit', this.submit.bind(this));
  },
  
  validate: function() {
    var okay = true;
    
    this.unhighlight($('l-name'));
    this.unhighlight($('l-telephone'));
    this.unhighlight($('l-email'));
    
    if($('name').value == '') {
      okay=false;
      this.highlight($('l-name'));
    }
    if($('telephone').value == '') {
      okay=false;
      this.highlight($('l-telephone'));
    } 
    if($('email').value == '' || ($('email').value.indexOf('@') == -1 || $('email').value.indexOf('.') == -1)) {
      okay=false;
      this.highlight($('l-email'));
    }
    
    return okay;
  },
  
  highlight: function(obj) {
    Element.addClassName(obj, "highlight");
  },
  
  unhighlight: function(obj) {
    Element.removeClassName(obj, "highlight");
  },

  submit: function(event) {
    //if(!checkcontactform()) { Event.stop(event); return false; }
    
    if(!this.validate()) { Event.stop(event); return false; }
    
    new Effect.Appear($('spinner'));
    
    new Ajax.Request(this.url, {
      method: 'post',
      postBody: this.form.serialize(),
      onSuccess: function(t) { 
        // this.form.enable();
        new Effect.Fade($('spinner'), { duration: 0.25, queue: 'end' });
        new Effect.Fade($('submit'), { duration: 0.25, queue: 'end', afterFinish: function() {
        new Effect.Appear($('thankyou'), { duration: 0.25 });
        
        }});
      }.bind(this),
      onFailure: function(t) {
        this.form.enable();
        new Effect.Fade($('spinner'));
        alert('Request failed because: '+t.statusText);
      }
    });
    
    this.form.disable();
    Event.stop(event);
    return true;
  }
}

Event.observe(window, 'load', function() {
  if($('contact-form')) {
    new contactHandler('contact-form');
  }
});