X.SubscribeMe = Class.create(X.Signals,
{
  initialize: function(el)
  {
    this.element = $(el);
    this.element.down('a').observe('click', this.onOpenClick.bindAsEventListener(this));
    this.element.down('button').observe('click', this.onSubscribeClick.bindAsEventListener(this));
    this.element.down('form').observe('submit', this.onSubscribeClick.bindAsEventListener(this));
    this.element.down('.err').hide();
    this.element.down('.ok').hide();
  },

  onOpenClick: function(event)
  {
    event.stop();
    this.element.down('.form').addClassName('show');
    this.element.down('input[name="email"]').focus();
  },

  onSubscribeClick: function(event)
  {
    event.stop();
    var data = this.element.down('form').serialize(true);
    X._rpc.call('subscribe', this.onSubscribeFinish.bind(this), data.email, data.company);
  },

  onSubscribeFinish: function(retval, error)
  {
    if (error)
    {
      this.element.down('.err').update(error.message.escapeHTML()); 
      this.element.down('.err').show();
    }
    else
    {
      this.element.down('.err').hide();
      this.element.down('.ok').show();
      this.element.down('.err').update(); 
      this.element.down('.ok').update('Registrace proběhla úspěšně, děkujeme vám! Pokud chcete být informováni i o jiných letácích, klikněte <a href="'+PREFIX+'registrace">zde</a>.'); 
      this.element.down('form').hide();
    }
  }
});

document.observe('dom:loaded', function() {
  X._rpc = new X.JsonRPC(PREFIX+'.rpc.');
  $$('.subscribe_me').each(function(el) {
    new X.SubscribeMe(el);
  });
});

