var ContactForm = {
  uri: null,
  spinner: null,
  spinner_blue: null,
  
  init: function() {
    if (!$('cformlink')) return; // cancel init if there're no form on the page
    
    // Preload the spinner image
    this.spinner = new Element('img', { 'src': '/images/spinner.gif'});
    this.spinner_blue = new Element('img', { 'src': '/images/spinner_blue.gif'});
    
    // Get the uri and form link
    this.uri = new URI(window.location);
    var formlink = $('cformlink');

    formlink.addEvent('click', function(event) {
      if (event) event.stop();
      // Hide the form link
      formlink.setStyle('display', 'none');
      
      // Put the form div after it
      var formdiv = new Element('div', {
        'id': 'cform',
        'html': '<img src="/images/spinner.gif" width="32" height="32" alt="Loading..."/>'
      });
      formdiv.inject(formlink.getParent('blockquote'), 'after');
      
      // And pull it's content from the server
      var contacturl = "/"+this.language()+"/contact_form";
      new Request.HTML({
        update: 'cform',
        onSuccess: this.prepareForm.bind(this)
      }).get(contacturl);
    }.bindWithEvent(this));
    
    if (this.uri.get('fragment') == 'form') formlink.fireEvent('click');
  },
  
  // Prepare the contact form
  prepareForm: function(rqtree, rqelms, rqhtml) {
    // Create the recaptcha
    Recaptcha.create('6LdZTwkAAAAAALoAwhzsRSYYHrPcjdCpxihpzVNk',
      'captcha', {
      'lang': this.language(),
      'theme': 'white'
    });
    
    // And set the event listener
    $('cformel').addEvent('submit', this.sendForm.bindWithEvent(this));
  },
  
  // Verifies and sends the filled in contact form
  sendForm: function(event) {
    if (event) event.stop();
    var form = $('cformel');
    
    // replace submit button with a spinner
    $('contact_submit').empty();
    $('contact_submit').grab(this.spinner_blue.clone());
    
    new Form.Request(form, 'cform', {
      onSuccess: function() { if ($('cform')) ContactForm.prepareForm.bind(this).run(); }.bind(this)
    }).send();
    return false;
  },
  
  // Find out the current language from the url
  language: function() {
    var lang = this.uri.get('directory').split("/")[1];
    return lang;
  }
};

window.addEvent('domready', ContactForm.init.bind(ContactForm));