// Signup form validation
// requires Prototype
var SignupForm = {
  errors: ['user_fullname',
           'username',
           'email',
           'email_confirmation',
           'password',
           'password_confirmation',
           'terms'],
  _num_invalid: 0,
  focus_background_color:   '#FFFFFF',
  focus_border_color:       '#9EC1E1',
  invalid_background_color: '#FF976F',
  invalid_border_color:     '#FC3C3C',
  valid_html: '<img src="/images/sign-up-yes.png" alt="Looks good!" />',
  invalid_html: '<img src="/images/sign-up-no.png" alt="Oye Vay!"/>',
  
  // These are run after the window is completely loaded
  bootstrap: function(){
    new Form.Element.Observer('user_fullname', 0.5, function(element, value) {
      SignupForm.fullname(value);
    });

    new Form.Element.Observer('user_username', 0.5, function(element, value) {
      SignupForm.username(value);
    });

    new Form.Element.Observer('user_email', 0.5, function(element, value) {
      SignupForm.email(value);
    });

    // new Form.Element.Observer('user_email_confirmation', 0.5, function(element, value) {
    //  SignupForm.email_confirmation(value);
    // });

    new Form.Element.Observer('user_password', 0.5, function(element, value) {
      SignupForm.password(value);
    });

    new Form.Element.Observer('user_password_confirmation', 0.5, function(element, value) {
      SignupForm.password_confirmation(value);
    });
    
    
    $('user_terms').onclick = function() {
      SignupForm.terms();
    }

    $('signup').onsubmit = function() {
      return SignupForm.is_valid();
    }

    var inputs = [$('signup').getInputs('text'), $('signup').getInputs('password')].flatten();
    inputs.each(function(elem){
      elem.onfocus = function() {
        this.original_background = this.style.background;
        this.original_border_color = this.style.borderColor;
        this.style.background = SignupForm.focus_background_color;
        this.style.borderColor = SignupForm.focus_border_color;
      }
      elem.onblur = function() {
        this.style.background = this.original_background;
        this.style.borderColor = this.original_border_color;
      }
    });
    
  },
  
  // runs each validation
  is_valid: function(){
    SignupForm._num_invalid = 0; // reset the validation counter
    $('signup').getInputs().each(function(elem){
      elem.id.sub(/user_(.*)/, function(match){
          if (SignupForm[match[1]] != undefined) {
            eval("SignupForm."+match[1]+"('"+elem.value+"')");
          }
      });
    });
    
    if (SignupForm._num_invalid > 0) {
      alert('Woah, there are like '+SignupForm._num_invalid+' errors with that form!');
      return false;
    }
    return true;
  },
  
  display_message: function(field) {
    // assume form field is user_*field*
    // and error message field is user_*field*_message
    if (SignupForm.errors[field].length > 0) {
      SignupForm._num_invalid += 1;
      $(field+'_message').innerHTML = SignupForm.invalid_html + 
        SignupForm.errors[field][SignupForm.errors[field].length-1];
    }
    else {
      $(field+'_message').innerHTML = SignupForm.valid_html;
    }
  },
  
  fullname: function(value) {
    SignupForm.errors['user_fullname'] = [];
    
    if (value.length < 4 || value.length > 100) {
      SignupForm.errors['user_fullname'].push('Your name needs to be more than 4 characters.');
    }
    
    // Display message
    SignupForm.display_message('user_fullname');
  },
  
  username: function(value) {
    SignupForm.errors['user_username'] = [];
    
    if (value.length < 4 || value.length > 100) {
      SignupForm.errors['user_username'].push('Your username needs to be more than 4 characters.');
    }
    
    // Validate uniqueness
    var url = '/users/check_input?username=' + encodeURIComponent(value);
    new Ajax.Request(url, {
      method: 'get',
      asynchronous: true,
      onSuccess: function(transport) {
        if (transport.responseText == 'false') {
          SignupForm.errors['user_username'].push('Someone has already taken this username.');
        }
      },
      onComplete: function(transport) {
        // Display message even if the ajax response failed
        SignupForm.display_message('user_username');
      }
    });
  },
  
  email: function (value) {
    SignupForm.errors['user_email'] = [];

    // Validate email format
    if (!value.match(/(^([^@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i)) {
      SignupForm.errors['user_email'].push("Hold it, this isn't an email address!");
    }

    // Validate length
    if (value.length < 4 || value.length > 100) {
      SignupForm.errors['user_email'].push('Your email needs to be more than 4 characters.');
    }
    
    // Validate uniqueness
    var url = '/users/check_input?email=' + encodeURIComponent(value);
    new Ajax.Request(url, {
      method: 'get',
      asynchronous: true,
      onSuccess: function(transport) {
        if (transport.responseText == 'false') {
          SignupForm.errors['user_email'].push('Someone has already taken this email.');
        }
      },
      onComplete: function(transport) {
        // Display message even if the ajax response failed
        SignupForm.display_message('user_email');
      }
    });
  },
  
  email_confirmation: function(value) {
    SignupForm.errors['user_email_confirmation'] = [];
    
    // Validate emails match
    if (value != $('user_email').value) {
      SignupForm.errors['user_email_confirmation'].push("This doesn't match what you entered above.");
    }
    
    if (value == '') {
      SignupForm.errors['user_email_confirmation'].push("This can't be blank.");
    }
    
    // Display message
    SignupForm.display_message('user_email_confirmation');
  },
  
  password: function(value) {
    SignupForm.errors['user_password'] = [];
    
    // Validates length
    if (value.length < 6 || value.length > 100) {
      SignupForm.errors['user_password'].push('Your password has to be at least 6 characters.');
    }
    
    if (value.match(/\s/)) {
      SignupForm.errors['user_password'].push('Your password cannot have any spaces.');
    }
    
    // Display message
    SignupForm.display_message('user_password');
  },
  
  password_confirmation: function(value) {
    SignupForm.errors['user_password_confirmation'] = [];
    
    // Validate emails match
    if (value != $('user_password').value) {
      SignupForm.errors['user_password_confirmation'].push("This doesn't match what you entered above.");
    }
    
    if (value == '') {
      SignupForm.errors['user_password_confirmation'].push("This can't be blank.");
    }
    
    // Display message
    SignupForm.display_message('user_password_confirmation');
  },
  
  terms: function() {
    SignupForm.errors['user_terms'] = [];
    
    // Check to ensure the terms were accepted
    if (!$('user_terms').checked) {
      SignupForm.errors['user_terms'].push("<span>Sorry, but you need accept the terms.</span>");
    }
    SignupForm.display_message('user_terms');
  }
}

Event.observe(window, 'load', SignupForm.bootstrap);