window.addEvent('domready', function() {

  $$('.request-invite').addEvent('click', function(e) {
    e.preventDefault();
    InvitationRequest.open();
  });

  /* check GET, auto-open from meylah blog */
  if (inviteMe)
    InvitationRequest.open();
});


var InvitationRequest = {
  open: function()
  {
    // Create the form
    this.form = new Element('form', {action: '/invitation', method: 'post'})  // Form element
    .adopt(new Element('div', {'class': 'message'}).adopt(new Element('h2', {text: 'request your invite now'})))  // Message element
    .adopt(new Element('input', {type: 'text', id: 'email', name: 'email', 'class': 'required validate-email', alt: 'enter your email here...'}))  // Email input
    .adopt(
      new Element('button', {type: 'submit', text: 'GO!'})  // Go button
      .adopt(new Element('span', {'class': 'icon'}))  // Icon for button
    );

    var validation = new Form.Validator.Inline(this.form, {
      scrollToErrorsOnSubmit: false,
		errorPrefix: '',
      onFormValidate: function(passed, formElem, e)
      {
        e.preventDefault();
        if (passed)
          this.submit();
      }.bind(this)
    });

    // Open the popup with form
    SqueezeBox.open(this.form, {
      handler: 'adopt',
      size: {x: 426, y: 245},
      onOpen: function()
      {
        this.content.addClass('request-invite-form');
  		autoFocus();
      }
    });


  },

  submit: function()
  {
    new Request({
      url: '/invitation',
      onRequest: function()
      {
        this.setMessage('Please wait...');
      }.bind(this),

      onSuccess: function(result)
      {
        this.setMessage(result);

        // Close the squeezebox after 3 seconds
        (function() { SqueezeBox.close(); }).delay(3000);
      }.bind(this),

      onFailure: function()
      {
        this.setMessage('There was an error. Please try again.');
        // Close the squeezebox after 3 seconds
        (function() { SqueezeBox.close(); }).delay(3000);
      }.bind(this)
    }).post(this.form);
  },

  setMessage: function(text)
  {
    if (text)
    {
      this.form.getElement('.message').set('html', text);
      this.form.addClass('working');
    }
    else
    {
      this.form.getElement('.message').set('html', 'request your invite now');
      this.form.removeClass('working');
    }
  }
};


function autoFocus() {
	$$('input[type=text]').each(function(input){
		var alt = input.get("alt");
		if(alt){
			var value = input.get("value");
			if (value == "") input.set("value", alt);
			input.addEvents({
				focus: function(){ if (this.get('value') == alt) this.set("value", ""); },
				blur: function(){ if (this.get('value') == "") this.set("value", alt);  }
			});
		}
	});
}
